我有這個代碼:
import pandas as pd
import os
ext = ('.tsv')
for files in os.listdir(os.getcwd()):
if files.endswith(ext):
x = pd.read_table(files, sep='\t', usecols=['#Chrom','Pos','RawScore','PHRED'])
x.drop_duplicates(subset ="Pos",keep = False, inplace = True)
data_frame=x.head()
print(data_frame)
#Chrom Pos RawScore PHRED
77171 6 167709702 7.852318 39.0
19180 6 31124849 7.623789 38.0
15823 6 29407955 6.982213 37.0
19182 6 31125257 6.817868 36.0
19974 6 31544591 6.201438 35.0
#Chrom Pos RawScore PHRED
52445 9 139634495 6.950686 36.0
46470 9 125391241 5.477094 34.0
49866 9 134385435 4.841222 33.0
48642 9 131475583 4.357986 31.0
40099 9 113233652 4.284035 31.0
#Chrom Pos RawScore PHRED
7050 13 32972626 6.472542 36.0
32416 13 100518634 5.405765 33.0
10834 13 42465713 4.406294 32.0
9963 13 39422624 4.374808 31.0
22993 13 76395620 4.193058 29.4
可以想象,我得到了多個具有相同列名但來自不同染色體的資料框。如何在不同的 csv 檔案中獲取多個資料幀?
uj5u.com熱心網友回復:
您可以使用熊貓的 pandas.DataFrame.to_csv ( https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.to_csv.html )將資料幀保存到 .csv 。更具體地說,在您的情況下,您可以這樣做:
for files in os.listdir(os.getcwd()):
if files.endswith(ext):
x = pd.read_table(files, sep='\t', usecols=
['#Chrom','Pos','RawScore','PHRED'])
x.drop_duplicates(subset ="Pos",keep = False, inplace = True)
x.to_csv(f'Chrom{x.iloc[0,0]}.csv')
在這里,x.iloc[0,0]將采用第一列的第一個元素,即#Chrom。您也可以手動執行此操作。請注意,如果您想擁有兩個具有相同 #Chromosome 的不同 DataFrame,則此方法將不起作用。在這種情況下,您必須手動輸入 csv 檔案的名稱。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/365278.html
