繁体   English   中英

根据第二个 dataframe 中的行设置 Pandas 一个 dataframe 中的值

[英]Set values in Pandas one dataframe based on rows in second dataframe

我有两个数据框 df1 和 df2,我想在 df1 中创建一个新列,并将该列中的值设置为 0,其中 df1 中的行包含在 df2 中。 进一步来说:

sample_data_1 = {'col1': ['80', '8080'], 'col2': ['0.0.0.0', '143.21.7.165']}
df1 = pd.DataFrame(data=sample_data_1)

sample_data_2 = {'col1': ['80', '8080', '1', '8888'], 'col2': ['0.0.0.0', '143.21.7.165', '1', '5.5.5.5'], 'col3': ['1','2','3']}
df2 = pd.DataFrame(data=sample_data_2)



     col1          col2
0    80         0.0.0.0
1  8080    143.21.7.165

   col1          col2 col3
0    80       0.0.0.0    1
1  8080  143.21.7.165    2
2     1             1    3
3  8888       5.5.5.5    4

我想向 df1 添加一列并将这些值设置为 0,其中 df1 中的 col1 和 col2 匹配 df2 中的 col1 和 col2。 结果 dataframe 应如下所示:

    col1          col2    score
0    80         0.0.0.0   0
1  8080    143.21.7.165   0

当 dataframe 尺寸相同时,我可以使用.loc function 和逻辑与进行直接比较,但是当它们具有不同的形状时,我会得到“无法比较系列”的异常。 想法?

谢谢您的帮助!

您可以使用df.merge

In [2735]: df1 = df1.merge(df2, on=['col1','col2']).drop('col3',1).assign(score=0)

In [2737]: df1 
Out[2737]: 
   col1          col2  score
0    80       0.0.0.0      0
1  8080  143.21.7.165      0

如果 col1 中的条目不相同,则可以将 col1 设置为索引。 恰恰:

df = df2.set_index('col1').reindex(df1.set_index('col1').index)
df['score']=0
df.reset_index(inplace=True)

通过压缩df1, df2中的公共列来检查成员资格 这将返回 boolean

使用np.where(condition, if condition, not condition) ,计算您想要的 output

import numpy as np

df1['score']=np.where([x in y for x,y in zip(df1.col1,df2.col1)],0,'not available')

    col1     col2          score
0   80      0.0.0.0         0
1   8080    143.21.7.165    0

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM