Skip to main content
 首页 » 编程设计

python之使用 Python 数据框从 csv 文件更新数据

2024年12月31日9shanyou

我正在从许多 CSV 文件中提取数据并将其保存到一个文件中。这个过程是重复的,而且每隔一段时间,我就会有新版本的文件,因此需要更新基础数据。我很难获得所需的数据。这是我正在尝试做的一个例子:

旧文件 (/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。所需的输出应该:

  1. 包含 test1.csv 和 test2.csv 中的所有列和行
  2. 在 test2.csv 中包含来自 test1.csv 的(行,列)对的更新数据
  3. 如果 test1.csv 中的 (row,col) 对没有更新,则应使用 test1.csv 中的数据。
  4. 更新文件中的任何空单元格都应填充 0。

对于上面显示的数据,这应该是 更新文件 (Test1_update.csv)

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 

请您参考如下方法:

我能够获得所需的数据框。

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))) 
df2 = df2.reindex(new_index) 
df2 = df2.join(df1, rsuffix='_P') 
df2 = df2.loc[:,~df2.columns.str.endswith('_P')].fillna(df1).fillna(0) 
df2.sort_index(inplace=True) 
print df2.to_string() 
 
 
       col2  col3  col4  col1                         
test1     8     7    15    11 
test3     5     9    10     9 
test5     9    -1     0    12 
test7     1     4     9     0 
test9    11    10    12     0