我有两个不同的数据框,如下图所示,
df1:
class name
0 I {'tom':2,'sam':14}
1 II {'ram':11,'joe':1}
df2:
class school area name
0 I mount north view, ca {'tom':0,'sam':0,'keith':0,'jhon':0}
1 II zion garden city, sa {'rita':0,'tommy':0,'kelvin':0,'ram':0,'joe':0}
如何比较df1和df2并更新学区和面积列,并假设结果为df1?
df1:
class school area name_1 name_2
0 I mount north view, ca {'tom':2,'sam':14} {'tom':0,'sam':0,'keith':0,'jhon':0}
1 II zion garden city, sa {'ram':11,'joe':1} {'rita':0,'tommy':0,'kelvin':0,'ram':0,'joe':0}
如何在下面的表达式中使用此条件,或者还有其他方法可以实现?
df1 = df1.merge(df2, how='left')
答案 0 :(得分:1)
这达到目的了吗?请注意,我更改了df2
的最后一行,以查看是否正确填充了None值。
df1 = pd.DataFrame({'class':[1,2], 'name': [{'tom':2,'sam':14},{'ram':11,'joe':1}]})
df2 = pd.DataFrame({'class':[1,2], 'school': ['mount','zion'], 'area':['north view, ca', 'garden city, sa'], 'name': [{'tom':0,'sam':0,'keith':0,'jhon':0}, {'rita':0,'tommy':0,'kelvin':0,'ram':0}]})
df1["name_concat"] = df1["name"].apply(lambda x: tuple(x.keys()))
df2["name_concat"] = df2["name"].apply(lambda x: tuple(x.keys()))
df = df1.merge(df2, how='left', on='class', suffixes=['_1', '_2'])
df[["school", "area"]] = df.apply(
lambda x: x[["school", "area"]] if all(x1 in x["name_concat_2"] for x1 in x["name_concat_1"]) else [None,None], axis=1)
print(df)