对熊猫的敏锐,
我试图用另一个数据帧更新一个简单的数据帧,结果遇到了麻烦。我有一个要更新的主数据帧:
主人公:
color tastey
name
Apples Red Always
Avocados Black Sometimes
Anise Brown NaN
我有一些新的数据,我想用它更新这个数据框。它可能追加新列、添加新行或更新旧值:
新数据框:
color tastey price
name
Bananas Yellow NaN Medium
Apples Red Usually Low
Berries Red NaN High
我想合并这两个数据帧,以便更新后的数据帧看起来像:
期望值:
color tastey price
name
Apples Red Always Low
Avocados Black Sometimes NaN
Anise Brown NaN NaN
Bananas Yellow NaN Medium
Berries Red NaN High
我玩过不同的命令,但我仍在努力:
不会丢失我加入的索引值。
将公共列组成一个tastey列,而不是tastey x和tastey y。
从新行中获取新数据。
不必硬编码新列或新行的名称。
最后(虽然本例中没有显示)我需要在多个列上联接。也就是说,我需要使用3列来形成我的唯一键。(尽管我相信上述示例的解决方案会扩展到这种情况。)
我衷心感谢您的帮助和指点!我希望上面的例子是清楚的。
干杯,
熊猫针头。
编辑1:我认为这个问题与以前的问题不同,因为当我使用
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
Edit3: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)
最佳答案
您可以在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