【问题标题】:updating data from csv files using Python dataframe使用 Python 数据框从 csv 文件更新数据
【发布时间】:2019-02-19 08:53:20
【问题描述】:

我正在从许多 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 的 (row,col) 对的更新数据
  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

【问题讨论】:

  • 我回顾了你的很多问题,但你从未提供过任何你尝试过的代码,只是一个你想要输出的列表。 SO 不是代码编写服务,分享您尝试过的代码,人们可以从那里帮助您。
  • 刚刚添加了我目前一直在尝试的代码。
  • 我当时转投赞成票。下班后我会看看,如果没有回答。这样做似乎很合理。

标签: python csv dataframe


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-13
    • 1970-01-01
    • 2018-07-04
    • 2014-02-07
    • 2018-09-18
    • 2021-02-06
    • 2017-03-29
    相关资源
    最近更新 更多