【发布时间】:2014-09-06 06:22:39
【问题描述】:
注意:为简单起见,我使用了一个玩具示例,因为在堆栈溢出中复制/粘贴数据帧很困难(如果有简单的方法,请告诉我)。
有没有办法在不获取 _X、_Y 列的情况下将一个数据帧中的值合并到另一个数据帧中?我希望一列上的值替换另一列的所有零值。
df1:
Name Nonprofit Business Education
X 1 1 0
Y 0 1 0 <- Y and Z have zero values for Nonprofit and Educ
Z 0 0 0
Y 0 1 0
df2:
Name Nonprofit Education
Y 1 1 <- this df has the correct values.
Z 1 1
pd.merge(df1, df2, on='Name', how='outer')
Name Nonprofit_X Business Education_X Nonprofit_Y Education_Y
Y 1 1 1 1 1
Y 1 1 1 1 1
X 1 1 0 nan nan
Z 1 1 1 1 1
在上一篇文章中,我尝试了 combine_First 和 dropna(),但这些都不起作用。
我想用 df2 中的值替换 df1 中的零。 此外,我希望根据 df2 更改具有相同名称的所有行。
Name Nonprofit Business Education
Y 1 1 1
Y 1 1 1
X 1 1 0
Z 1 0 1
(需要澄清:name = Z 的“Business”列中的值应该为 0。)
我现有的解决方案执行以下操作: 我根据 df2 中存在的名称进行子集化,然后将这些值替换为正确的值。但是,我想要一种不那么老套的方法来做到这一点。
pubunis_df = df2
sdf = df1
regex = str_to_regex(', '.join(pubunis_df.ORGS))
pubunis = searchnamesre(sdf, 'ORGS', regex)
sdf.ix[pubunis.index, ['Education', 'Public']] = 1
searchnamesre(sdf, 'ORGS', regex)
【问题讨论】:
-
我不太明白你的逻辑,你想用另一个 df 的匹配值更新第一个 df,然后你将 Z 的业务值设置为 1,对吗?原来是 0。