我有两个tsv文件,每个文件都有标题和列。文件A具有标题:SampleID & RawReads,FileB具有标题:SampleID & ReadsPost。我想将ReadsPost附加到FileA,以便数据与正确的SampleID对齐。将列从一个tsv文件添加到另一个(unix)
我原来的计划是在Python中使用字典来完成此操作,其中键是sampleID。但是,在bash中必须有一个更简单的方法来做到这一点!
任何帮助将是伟大的!
我有两个tsv文件,每个文件都有标题和列。文件A具有标题:SampleID & RawReads,FileB具有标题:SampleID & ReadsPost。我想将ReadsPost附加到FileA,以便数据与正确的SampleID对齐。将列从一个tsv文件添加到另一个(unix)
我原来的计划是在Python中使用字典来完成此操作,其中键是sampleID。但是,在bash中必须有一个更简单的方法来做到这一点!
任何帮助将是伟大的!
使用join
,做一个全外连接(或任何其他类型的连接):
>cat test.txt test2.txt
SampleID RawReads
1 18
2 15
5 21
7 7
SampleID ReadsPost
1 yes
3 no
4 yes
5 yes
> join -a1 -a2 test.txt test2.txt
SampleID RawReads ReadsPost
1 18 yes
2 15
3 no
4 yes
5 21 yes
7 7
注:从没有加入文件中的-a参数打印线。为了完成一个完整的外连接,从两个文件中打印行,如示例所示。
使用pandas.read_csv
加载您的数据,您可能必须为制表符分隔的工作表设置sep='\t'
。一旦你有两个DataFrames加载,你可以使用pandas.concat
或pandas.merge
。请参阅Pandas文档中的Merge, join, and concatenate。
比方说,你的两个TSV”是这样的:
文件1:
SampleID RawReads
1 18
2 15
5 21
7 7
文件2:
SampleID ReadsPost
1 yes
3 no
4 yes
5 yes
使用合并
合并可以被用来实现两个DataFrame上的数据库样式连接。在我们的例子中,我们可以看到两个DataFrame在SampleID列中不一致。如果我们要确保从两个帧中获得所有数据,我们将使用outer
连接。如果我们只需要一个或另一个的数据,我们可以使用right
或left
加入,这取决于我们想要保留的内容。这是一个保持一切的例子。
df1 = pd.read_csv(file1, sep='\t')
df2 = pd.read_csv(file2, sep='\t')
merge_df = pd.merge(df1, df2, how='outer', on='SampleID')
print(merge_df)
SampleID RawReads ReadsPost
0 1 18.0 yes
1 2 15.0 NaN
2 5 21.0 yes
3 7 7.0 NaN
4 3 NaN no
5 4 NaN yes
使用的毗连
的毗连可用于沿任行或列轴线延伸DataFrames。假设SampleID是您的索引,并且您只是想将file2中的值沿列轴连接到file1。例如:
df1 = pd.read_csv(file1, sep='\t', index_col='SampleID')
df2 = pd.read_csv(file2, sep='\t', index_col='SampleID')
concat_df = pd.concat([df1, df2], axis=1)
print(concat_df)
RawReads ReadsPost
SampleID
1 18.0 yes
2 15.0 NaN
3 NaN no
4 NaN yes
5 21.0 yes
7 7.0 NaN
就像我说的阅读熊猫文档。这是一个非常强大的库,也是在python中处理数据的好工具。
谢谢!两个答案都很完美。我使用了熊猫选项,因此我可以用Rawpads和ReadsPost与matplotlib构建一个分组条形图。 –