![](/img/trans.png)
[英]combining one-column text files into one multi-column file, separated by tabs
[英]How to replace multi-column from one text file to a column in another text file?
我有:
$ cat file1.csv (tab delimited)
R923E06 273911 2990492 2970203 F Resistant
R923F06 273910 2990492 2970203 F Resistant
R923H02 273894 2970600 2990171 M Resistant
和:
$ cat file2.txt (space delimited and it's a large file)
R923E06 CC GG TT AA ...
R923F06 GG TT AA CC ...
R923H02 TT GG CC AA ...
我怎样才能在更换第一列的file2.txt
所有6列file1.csv
?
使用join
可以做到这一点:
join <(sed -e 's/\t/ /g' file1.csv) <(cat file2.txt)
sed
将制表符更改为空格
join
到同一字段上两个文件的连接行。
输出:
R923E06 273911 2990492 2970203 F Resistant CC GG TT AA ...
R923F06 273910 2990492 2970203 F Resistant GG TT AA CC ...
R923H02 273894 2970600 2990171 M Resistant TT GG CC AA ...
看一下这个AWK示例:
awk 'FNR == NR { d[$1] = $0; next } { $1 = d[$1] } 1' file1.csv file2.txt
在这里,我取代第一列file2.txt
与相应的线(6列) file1.csv
。
输出:
R923E06 273911 2990492 2970203 F Resistant CC GG TT AA ...
R923F06 273910 2990492 2970203 F Resistant GG TT AA CC ...
R923H02 273894 2970600 2990171 M Resistant TT GG CC AA ...
如果要在结果中用制表符分隔所有内容,则可以添加gsub(/[[:space:]]/,"\\t")
以制表符替换任何空格或制表符:
awk 'FNR == NR { d[$1] = $0; next } { $1 = d[$1]; gsub(/[[:space:]]/,"\t") } 1' file1.csv file2.txt
#import pandas
import pandas as pd
#read file1.csv
#set index_col as false if file has delimiters at the end
file1 = pd.read_csv( 'file1.csv', ' ', index_col = False, names =
['1','2','3','4','5','6']);
#read file2.txt, read_csv can read txt files as well
#set index_col as false if file has delimiters at the end
file2 = pd.read_csv( 'file2.csv', ' ', index_col = False, names =
['1','2','3','4','5']);
#drop first column
file2.drop( '1', axis = 1, inplace = True )
#concat both frames
final = pd.concat([file1, file2], axis = 1)
#you might end up with mixed column names you can change it by using
final.columns = ['col1', 'col2', ....]
#save as csv
final.to_csv('out.csv',sep='\t')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.