我正在从许多CSV文件中提取数据并将其保存到一个文件中。这个过程是重复的,每隔一段时间,我会有新版本的文件,因此底层数据需要更新。我很难得到所需的数据。这里是我试图做的一个例子:
旧文件(/old/Test1.csv)
请注意,在新文件中,col1不再存在,有一个新的列col4,行test5不存在,而有两个新的行test7和test9。期望的输出应该是:
旧文件(/old/Test1.csv)
tests col1 col2 col3
test1 11 8 5
test3 9 5 7
test5 12 9 -1
新文件 (/new/Test1.csv)
tests col2 col3 col4
test1 8 7 15
test3 5 9 10
test7 1 4 9
test9 11 10 12
请注意,在新文件中,col1不再存在,有一个新的列col4,行test5不存在,而有两个新的行test7和test9。期望的输出应该是:
- 包含test1.csv和test2.csv中的所有列和行
- 包括来自test1.csv的(row,col)对的更新数据
- 如果test1.csv中的(row,col)对没有更新,则应使用test1.csv中的数据。
- 更新文件中的任何空单元格应填充为0。
tests col1 col2 col3 col4
test1 11 8 7 15
test3 9 5 9 10
test5 12 9 -1 0
test7 0 1 4 9
test9 0 11 10 12
我通过下面的代码可以到达这个点:
tests col1 col2 col3 col4
test1 Nan 8 7 15
test3 Nan 5 9 10
test5 Nan Nan Nan Nan
test7 Nan 1 4 9
test9 Nan 11 10 12
import pandas as pd
import numpy as np
df1 = pd.read_csv('\\dir\\test1.csv', index_col=0)
df2 = pd.read_csv('\\dir\\test2.csv', index_col=0)
new_index = list(set(list(df1.index.values)+list(df2.index.values)))
new_cols = list(set(list(df1.columns.values)+list(df2.columns.values)))
df3 = pd.DataFrame(index=new_index, columns=new_cols)
df4 = df2.reindex(df3.index)
df4 = df4.join(df3, rsuffix='_P')
df4 = df4.loc[:,~df4.columns.str.endswith('_P')]
print df4