我有以下数据框:
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:列表索引超出范围
最佳答案
如果使用 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]))
关于python - 如何根据Python中其他列的条件将字符串列拆分为另一列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57357663/