python - 如何使用 python 比较同一数据框中的两列来创建新列?

标签 python python-3.x pandas jupyter-notebook

我有如下所示的数据框。 df:

col_1 col_2 
EDU   facebook
EDU   google
EDU   google_usa
EDU   tabula
EDU   xyz
EDU   abc
IAR   facebook
IAR   google

如果 col_1 有 'EDU' 并且 col_2 有 'facebook', 'google' new_col 应该有相同的字符串,即 facebook 和 google ,如果 col_2 包含 'google_usa',tabula' new_col 应包含 'gusa',并且如果 col_2 包含任何其他字符串 ne_col 应在同一数据框中包含 others。 如果 col_1 具有“IAR”且 col_2 具有 'facebook' new_col 应具有 facebook,并且对于 col_2 中的任何其他字符串code> 它应该在同一数据框中包含 'other'

预期输出:

col_1   col_2     new_col
EDU   facebook    facebook
EDU   google      google
EDU   google_usa  gusa
EDU   tabula      gusa
EDU   xyz         others
EDU   abc         others
IAR   facebook    facebook
IAR   google      others

我尝试了下面的代码,但没有成功。请在这方面帮助我。 提前致谢。

if df['col_1'].str.contains('EDU').any():

        df['new_col'] = ['facebook' if 'facebook' in x else
                            'google' if 'google' == x else
                            'gcusa_tb' if 'taboola' in x else
                            'gcusa_tb' if 'google_cusa' in x else
                            'Others' for x in df['col_2']]

最佳答案

is_edu = df.col_1 == 'EDU'
g_or_f = df.col_2.isin(['google', 'facebook'])
g_or_t = df.col_2.isin(['google_usa', 'tabula'])
is_iar = df.col_1 == 'IAR'
is_fac = df.col_2 == 'facebook'

df.assign(
    new_col=np.where(
        is_edu,
        np.where(
            g_or_f, df.col_2,
            np.where(g_or_t, 'gusa', 'other')
        ),
        np.where(
            is_iar & is_fac, 'facebook', 'other'

        )
    )
)

  col_1       col_2   new_col
0   EDU    facebook  facebook
1   EDU      google    google
2   EDU  google_usa      gusa
3   EDU      tabula      gusa
4   EDU         xyz     other
5   EDU         abc     other
6   IAR    facebook  facebook
7   IAR      google     other

关于python - 如何使用 python 比较同一数据框中的两列来创建新列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42909161/

相关文章:

python - 如何仅将 'Unnamed:' 列重命名为数字索引

python - 自定义 django-admin 模板

python - Django 1.9.2 断言错误 : database connection isn't set to UTC

python - 如何在一定数量的请求后停止 scrapy 蜘蛛?

python - Python中是否存在可变命名元组?

python-3.x - 使用 Pandas 与 DataFrames 合并时出现 ValueError

python - 如何从 Cython 中的另一个线程设置 future\add 到队列的结果?

python - 有没有一个好的工具来聚合站点的 django 错误消息?

python-3.x - 使用 Bottle.py 提供嵌套的静态文件

list - 当列数据类型为列表时如何过滤 Pandas 数据框