[英]Compare one column (vector) from one CSV file with two columns (vector and array) from another CSV file using Python 3.8
我是初學者,正在尋找解決方案。 我正在嘗試比較兩個 CSV 文件中沒有 header 的列。 第一個有一個列,第二個有兩個。
File_1.csv : #包含 2k 行隨機數。
1
4
1005
.
.
.
9563
File_2.csv : #Contains 28k 行
0 [81,213,574,697,766,1074,...21622]
1 [0,1,4,10,12,13,1005, ...31042]
2 [35,103,85,1023,...]
3 [4,24,108,76,...]
4 []
.
.
.
28280 [0,1,9,10,32,49,56,...]
我想首先將 File_1 的列與File_2的第一列進行比較,看看它們是否匹配並將匹配值加上 file2 的第二列提取到一個新的 CSV 文件(output.csv)中,刪除不匹配的值。 例如,
output.csv:
1 [0,1,4,10,12,13,1005, ...31042]
4 []
.
.
.
其次,我想將File_1.csv列(迭代 2k 行)與output.csv的第二列(每個數組)進行比較進入output.csv文件並保留該文件的第一列。 例如, 4 被刪除,因為它在第二列(數組)中沒有任何值,因為沒有數字可與File_1進行比較,但還有其他類似 1 的值確實有一些匹配“
output.csv:
1 [1,4,1005]
.
.
.
我找到了適用於第一步的代碼,但它不保存第二列。 我一直在研究如何比較 arrays,但我沒能做到。 這是我目前所擁有的
import csv
nodelist = []
node_matches = []
with open('File_1.csv', 'r') as f_rand_node:
csv_f = csv.reader(f_rand_node)
for row in csv_f:
nodelist.append(row[0])
set_node = set(nodelist)
with open('File_2.csv', 'r') as f_tbl:
with open('output.csv', 'w') as f_out:
csv_f = csv.reader(f_tbl)
for row in csv_f:
set_row = set(' '.join(row).split(' '))
if set_row.intersection(set_node):
node_match = list(set_row.intersection(set_node))[0]
f_out.write(node_match + '\n')
感謝您的幫助。
使用 pandas 數據幀,整個事情變得容易多了:
import pandas as pd
#Read the files into two dataFrames
df1= pd.read_csv("File_1.csv")
df2= pd.read_csv("File_2.csv")
df2.set_index("Column 0")
df2= df2.filter(items = df1)
index= df1.values()
df2 = df2.applymap(lambda x: set(x).intersection(index))
df.to_csv("output.csv")
這應該可以解決問題,非常簡單。
我建議在這種情況下使用pandas
。
文件_1.csv:
1
4
1005
9563
文件_2.csv:
0 [81,213,574,697,766,1074]
1 [0,1,4,10,12,13,1005,31042]
2 [35,103,85,1023]
3 [4,24,108,76]
4 []
5 [0,1,9,10,32,49,56]
代碼:
import pandas as pd
import csv
file1 = pd.read_csv('File_1.csv', header=None)
file1.columns=['number']
file2 = pd.read_csv('File_2.csv', header=None, delim_whitespace=True, index_col=0)
file2.columns = ['data']
df = file2[file2.index.isin(file1['number'].tolist())] # first step
df = df[df['data'] != '[]'] # second step
df.to_csv('output.csv', header=None, sep='\t', quoting=csv.QUOTE_NONE)
Output.csv:
1 [0,1,4,10,12,13,1005,31042]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.