![](/img/trans.png)
[英]how to split the string in one column and compare it with other column in Python
[英]How to split a string column into another one based on condition of other column in python?
我有以下数据框:
import pandas as pd
dt = pd.DataFrame({'col': ['A','A_B']})
我希望col==A
的rows
值all
放入一个新列( col2
)中,其余的进行str.split
操作
我希望最终的 df 看起来像这样:
dt = pd.DataFrame({'col': ['A', 'A_B'],
'col2': ['all', 'B']})
我试过:
dt['col2'] = np.where(dt.col == 'A', 'all',
dt.col.apply(lambda x: x.split('_')[1]))
但我收到此错误: IndexError: list index out of range
如果使用 pandas 文本函数,它在您的情况下工作正常 - 返回缺失值,因为第二个列表不存在:
print (dt.col.str.split('_').str[1])
0 NaN
1 B
Name: col, dtype: object
dt['col2'] = np.where(dt.col == 'A', 'all', dt.col.str.split('_').str[1])
print (dt)
col col2
0 A all
1 A_B B
或使用[-1]
选择拆分后的最后一个列表:
dt['col2'] = np.where(dt.col == 'A', 'all',
dt.col.apply(lambda x: x.split('_')[-1]))
或者是通过反转掩码可能的过滤器值:
m = dt.col == 'A'
dt['col2'] = np.where(m, 'all',
dt.loc[~m, 'col'].apply(lambda x: x.split('_')[1]))
你可以
dt['col2'] = dt.col.str.split('_', expand = True).fillna('all')[1]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.