Pandas检查多个行并复制不同的行

3

I've this following scenario.

Table 1

column_a column_b 
1         10
2         20
3         30
4         40

表格 2

column_a new_column 
1         10
2         20
3         30
5         0

如果两个表中的column_a的值匹配,new_column应该使用table 1 column_b中相应的值填充。如果不匹配,则应填充0。我可以在两个表上使用iterrows来完成此操作,但是否有更好/更有效的方法?谢谢。
4个回答

3

map + fillna

df2['new_col'] = df2.column_a.map(df1.set_index('column_a').column_b).fillna(0)

print(df2)
   column_a  new_col
0         1     10.0
1         2     20.0
2         3     30.0
3         5      0.0

2
另一个选项是合并(merge):最初的回答。
df2.merge(df, on='column_a', how='left')

   column_a  column_b
0         1      10.0
1         2      20.0
2         3      30.0
3         5       NaN

# add replace and rename if you want

df2.merge(df, on='column_a', how='left').replace(np.nan, 0).rename(columns={'column_b':'new_column'})

   column_a  new_column
0         1        10.0
1         2        20.0
2         3        30.0
3         5         0.0

2

Use np.where

df2.new_column = np.where(df1.column_a.eq(df2.column_a), df1.column_b, 0)

0

在导入模块并构建table1和table2之后,您可能需要像这样的东西 mask = table1['column_a']==table2['column_a'] table2.loc[mask,'new_column']= table1.loc[table1['column_a']==table2['column_a'],'column_b'] table2.loc[~mask,'new_column'] = 0 请注意,table1和table2是通过以下方式构建的 import pandas as pd table1 = pd.DataFrame({'column_a':[1,2,3,4],'column_b':[10,20,30,40]}) table2 = pd.DataFrame({'column_a':[1,2,3,5]})


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接