我有如下所示的数据框。 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/