![](/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.