python - 基于另一个数据框 python pandas 替换列值 - 更好的方法?

标签 python pandas

注意:为了简单起见,我使用了一个玩具示例,因为复制/粘贴数据帧在堆栈溢出时很困难(如果有简单的方法,请告诉我)。

有没有一种方法可以在不获取 _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

(需要澄清:名称 = Z 的“业务”列中的值应为 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)

最佳答案

注意:在最新版本的 pandas 中,以上两个答案都不再有效:

KSD 的回答会引发错误:

df1 = pd.DataFrame([["X",1,1,0],
              ["Y",0,1,0],
              ["Z",0,0,0],
              ["Y",0,0,0]],columns=["Name","Nonprofit","Business", "Education"])    

df2 = pd.DataFrame([["Y",1,1],
              ["Z",1,1]],columns=["Name","Nonprofit", "Education"])   

df1.loc[df1.Name.isin(df2.Name), ['Nonprofit', 'Education']] = df2.loc[df2.Name.isin(df1.Name),['Nonprofit', 'Education']].values

df1.loc[df1.Name.isin(df2.Name), ['Nonprofit', 'Education']] = df2[['Nonprofit', 'Education']].values

Out[851]:
ValueError: shape mismatch: value array of shape (2,) could not be broadcast to indexing result of shape (3,)

而 EdChum 的回答会给我们错误的结果:

 df1.loc[df1.Name.isin(df2.Name), ['Nonprofit', 'Education']] = df2[['Nonprofit', 'Education']]

df1
Out[852]: 
  Name  Nonprofit  Business  Education
0    X        1.0         1        0.0
1    Y        1.0         1        1.0
2    Z        NaN         0        NaN
3    Y        NaN         1        NaN

好吧,只有当“名称”列中的值是唯一的并且在两个数据框中都排序时,它才能安全地工作。

这是我的答案:

方式一:

df1 = df1.merge(df2,on='Name',how="left")
df1['Nonprofit_y'] = df1['Nonprofit_y'].fillna(df1['Nonprofit_x'])
df1['Business_y'] = df1['Business_y'].fillna(df1['Business_x'])
df1.drop(["Business_x","Nonprofit_x"],inplace=True,axis=1)
df1.rename(columns={'Business_y':'Business','Nonprofit_y':'Nonprofit'},inplace=True)

方式二:

df1 = df1.set_index('Name')
df2 = df2.set_index('Name')
df1.update(df2)
df1.reset_index(inplace=True)

More guide about update. .需要设置索引的两个数据框的列名在“更新”之前不必相同。您可以尝试“姓名 1”和“姓名 2”。此外,即使 df2 中有其他不必要的行也不会更新 df1,它也能正常工作。换句话说,df2 不需要是 df1 的超集。

例子:

df1 = pd.DataFrame([["X",1,1,0],
              ["Y",0,1,0],
              ["Z",0,0,0],
              ["Y",0,1,0]],columns=["Name1","Nonprofit","Business", "Education"])    

df2 = pd.DataFrame([["Y",1,1],
              ["Z",1,1],
              ['U',1,3]],columns=["Name2","Nonprofit", "Education"])   

df1 = df1.set_index('Name1')
df2 = df2.set_index('Name2')


df1.update(df2)

结果:

      Nonprofit  Business  Education
Name1                                
X           1.0         1        0.0
Y           1.0         1        1.0
Z           1.0         0        1.0
Y           1.0         1        1.0

关于python - 基于另一个数据框 python pandas 替换列值 - 更好的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24768657/

相关文章:

python - 两两相关

python-3.x - 如何删除并仅保留某些非字母数字字符?

Pandas:分组多列,找到最大值并将其他列保留在数据框中

python - 排序()返回无

python - 如何检查字典中是否存在具有特定模式的值?

python - login() 缺少 1 个必需的位置参数 : 'user'

python - 按组计算每行之后的行数

python - 如何为 python 应用程序的所有子项设置语言环境?

python - 使用 *args 对元组进行高级切片

python - 如何将字符串矩阵更改为整数矩阵