Pandas更新/替换另一个参考文件中的值

问题描述 投票:0回答:1

请根据另一个文件中的值帮助我更新文件。

我收到的文件是“ todays_file1.csv”,并具有下表:

name    day a_col   b_col   c_col
alex    22-05   rep 68  67
stacy   22-05   sme 79  81
penny   22-05   rep 74  77
gabbi   22-05   rep 59  61

因此,我只需要将['day','b_col','c_col']中的值更新到第二个文件“ my_file.csv”,该文件中的其他列过多。

name    day a_col   a_foo   b_col   b_foo   c_col
penny   21-May  rep 2   69  31  69
alex    21-May  rep 2   71  34  62
gabbi   21-May  rep 1   62  32  66
stacy   21-May  sme 3   73  38  78

我到目前为止拥有的代码如下:

df1 = pd.read_csv("todays_file1.csv")
df2 = pd.read_csv("my_file.csv")
df2.replace(to_replace=df2['day', 'b_col', 'c_col'], value= df1['day', 'b_col', 'c_col'], inplace=True)

[请帮忙,如何根据'name'列替换这3列,这在这两个列中都很常见,但可能会混杂在一起。

我收到以下错误:

Traceback (most recent call last):
  File "D:\TESTING\Trial.py", line 93, in <module>
    df2.replace(to_replace=df2['day', 'b_col', 'c_col'], value= df1['day', 'b_col', 'c_col'], inplace=True)
  File "C:\Winpy\WPy64-3770\python-3.7.7.amd64\lib\site-packages\pandas\core\frame.py", line 2800, in __getitem__
    indexer = self.columns.get_loc(key)
  File "C:\Winpy\WPy64-3770\python-3.7.7.amd64\lib\site-packages\pandas\core\indexes\base.py", line 2648, in get_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas\_libs\index.pyx", line 111, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\index.pyx", line 138, in pandas._libs.index.IndexEngine.get_loc
  File "pandas\_libs\hashtable_class_helper.pxi", line 1619, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas\_libs\hashtable_class_helper.pxi", line 1627, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: ('day', 'b_col', 'c_col')
python-3.x pandas replace keyerror
1个回答
0
投票

“ anky”通过评论提供了解决方案,非常感谢。

下面的代码有助于解决问题。

df1 = pd.read_csv("todays_file1.csv")
df2 = pd.read_csv("my_file.csv")
df1.set_index('name')
df2.set_index('name')
df2.update(df1)
df2.to_csv("my_file.csv", index=False)

再次感谢您Anky:)

© www.soinside.com 2019 - 2024. All rights reserved.