你和熊猫的敏感,
我试图用另一个数据框更新一个简单的数据框,但我遇到了麻烦。我有一个我想要更新的主数据框:
Master_df:
color tastey
name
Apples Red Always
Avocados Black Sometimes
Anise Brown NaN
我有一些新数据,我想用这个数据框更新。它可能会附加新列,添加新行或更新旧值:
New_df:
color tastey price
name
Bananas Yellow NaN Medium
Apples Red Usually Low
Berries Red NaN High
我想合并这两个数据框,以便更新的数据框如下所示:
Desired_df:
color tastey price
name
Apples Red Always Low
Avocados Black Sometimes NaN
Anise Brown NaN NaN
Bananas Yellow NaN Medium
Berries Red NaN High
我玩过https://github.com/trufflesuite/ganache-cli/issues/407#issuecomment-347663452个不同的命令,但我还在努力:
最后,(虽然未在此示例中显示)我需要加入多个列。即我需要使用3列来形成我的唯一键。 (虽然我确信上面例子的解决方案会扩展到那种情况。)
我衷心感谢任何帮助或指点!我希望上面的例子很清楚。
干杯,
熊猫针头。
edit1:我认为这个问题与之前提出的问题不同,因为当我使用combine_first
时,我得到了这个问题:
>>> Master_df.combine_first(New_df)
color tastey
name
Apples Red Always
Avocados Black Sometimes
Anise Brown NaN
编辑2:好的,我越来越近了,但还没有!我不想生成_x
和_y
列。我希望它们是一列,在发生冲突时从New_df
获取数据。
>>> updated = pd.merge(Master_df, New_df, how="outer", on=["name"])
name color_x tastey_x color_y tastey_y price
0 Apples Red Always Red Usually Low
1 Avocados Black Sometimes NaN NaN NaN
2 Anise Brown NaN NaN NaN NaN
3 Bananas NaN NaN Yellow NaN Medium
4 Berries NaN NaN Red NaN High
编辑3:many重要的是,我不必对列名进行硬编码(' A',' B'等等。)除了钥匙。
P.S。代码如下。
import pandas as pd
import numpy as np
Master_data = {
'name' : ['Apples', 'Avocados', 'Anise'],
'color' : ['Red', 'Black', 'Brown'],
'tastey' : ['Always', 'Sometimes', np.NaN]
}
Master_df = pd.DataFrame(Master_data, columns = ['name', 'color', 'tastey'])
Master_df = Master_df.set_index('name')
print(Master_df)
newData = {
'name' : ['Bananas', 'Apples', 'Berries'],
'color' : ['Yellow', 'Red', 'Red'],
'tastey' : [np.NaN, 'Usually', np.NaN],
'price' : ['Medium', 'Low', 'High']
}
New_df = pd.DataFrame(newData, columns = ['name', 'color', 'tastey', 'price'])
New_df = New_df.set_index('name')
print(New_df)
Desired_data = {
'name' : ['Apples', 'Avocados', 'Anise', 'Bananas', 'Berries'],
'color' : ['Red', 'Black', 'Brown', 'Yellow', 'Red'],
'tastey' : ['Always', 'Sometimes', np.NaN, np.NaN, np.NaN],
'price' : ['Low', np.NaN, np.NaN, 'Medium', 'High']
}
Desired_df = pd.DataFrame(Desired_data, columns = ['name', 'color', 'tastey', 'price'])
Desired_df = Desired_df.set_index('name')
print(Desired_df)
答案 0 :(得分:1)
您可以在 pd.DataFrame.update
之前使用pd.DataFrame.combine_first
(就地操作):
New_df.update(Master_df)
res = New_df.combine_first(Master_df)
# color price tastey
# name
# Anise Brown NaN NaN
# Apples Red Low Always
# Avocados Black NaN Sometimes
# Bananas Yellow Medium NaN
# Berries Red High NaN