我有两个csv文件,现在将它们称为csv1(Source,Destination,Bits,Energy,PktCount,Time)和csv2(Source,Destination,Bits,Energy,PktCount,Time)这样生成的新csv具有标头为(Address,Energy,Time)的标头,合并时将其从csv1的(Source,Energy,Time)列和csv2的(Destination,Energy,Time)列中获取。在python中实现?
CSV1:
Source,Destination,Bits,Energy,PktCount,Time
1,3,320,9.999983999999154773195,1,0
3,4,320,9.99996799947074134565,1,2319
1,3,320,9.999951999998309546390,2,7327
3,4,320,9.99993599894148269130,2,10365
2,3,384,9.999916799998736846248,1,12156
3,4,384,9.99989759830637230608,3,14999
1,3,320,9.999900799997464319585,3,15111
3,4,320,9.99986559777711365173,4,18112
1,3,320,9.999868799996619092780,4,22651
3,4,320,9.99983359724785499738,5,24974
1,3,320,9.999836799995773865975,5,30010
CSV2:
Source,Destination,Bits,Energy,PktCount,Time
1,2,320,9.999984,1,751
1,3,320,9.999984,1,1002
3,4,320,9.999984,1,3329
3,1,320,9.999967999999154773195,1,3408
3,2,320,9.999968,2,3458
1,2,320,9.999952,3,8135
1,3,320,9.99995199947074134565,2,8409
3,4,320,9.999968,2,11376
3,1,320,9.999935999998309546390,2,11441
3,2,320,9.999936,4,11504
2,1,384,9.999916799998309546390,3,12964
2,3,384,9.99991679894148269130,3,13293
3,4,384,9.9999488,3,16010
1,3,320,9.99988159830637230608,4,16181
3,4,320,9.9999328,4,19122
3,1,320,9.999884799997464319585,4,19187
3,2,320,9.999900799998736846248,5,19253
1,2,320,9.999884799998736846248,6,23458
1,3,320,9.99984959777711365173,5,23724
3,4,320,9.9999168,5,25981
所需的输出:
Address Energy Time
1 9.999984 0
3 9.999968 2319
1 9.999952 7327
2 9.999984 751
3 9.999984 1002
4 9.999984 3329
1 9.999968 3408
2 9.999968 3458
通过检查时间列,您可以检查是否从csv1中添加了某些行,并且从csv2中添加了某些行,顺序无关紧要。我只想将其合并。
这是我尝试过的方法,但它会覆盖以前的csv文件中的数据
import pandas as pd
import matplotlib.pyplot as plt
import csv
import numpy as np
df1 = pd.read_csv('C:\\Users\\Hp\\Documents\\XYZ.csv', usecols = ['Source','Energy','Time'])
df2 = pd.read_csv('C:\\Users\\Hp\\Documents\\XYZ1.csv', usecols = ['Destination','Energy','Time'])
np.savetxt('C:\\Users\\Hp\\Documents\\wee.csv', df1, delimiter =',')
with open('C:\\Users\\Hp\\Documents\\wee.csv') as f:
for _ in range(len(df1)):
next(f)
np.savetxt('C:\\Users\\Hp\\Documents\\wee.csv', df2, delimiter =',')