簡體   English   中英

如何將多列從一個文本文件替換為另一文本文件中的列?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM