![](/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.