3 回答

TA貢獻1835條經(jīng)驗 獲得超7個贊
您可以使用str.extract合適的regex. 這將找到周圍的所有值:(也去除冒號周圍的空格):
df[['Machine', 'Action']] = df.Description.str.extract('(.*) : (.*)',expand=True)
>>> df
Description Machine Action
0 Machine x : Turn off Machine x Turn off
1 Another action here NaN NaN
2 Another action here NaN NaN
3 Machine y : Turn off Machine y Turn off
4 Machine x : Turn on Machine x Turn on
5 Another action here NaN NaN
# df[['Machine', 'Action']] = df.Description.str.extract('(.*) : (.*)',expand=True).fillna('')

TA貢獻1844條經(jīng)驗 獲得超8個贊
只需使用split與expand=True
df[['Machine', 'Action']] =df.Description.str.split(':',expand=True).dropna()
df
Description Machine Action
0 Machine x : Turn off Machine x Turn off
1 Another action here NaN NaN
2 Another action here NaN NaN
3 Machine y : Turn off Machine y Turn off
4 Machine x : Turn on Machine x Turn on
5 Another action here NaN NaN

TA貢獻1757條經(jīng)驗 獲得超8個贊
給定一個數(shù)據(jù)框
>>> df
Description
0 Machine x : Turn off
1 Another action here
2 Another action here
3 Machine y : Turn off
4 Machine x : Turn on
5 Another action here
我會通過Series.str.split(splitter, expand=True).
>>> has_colon = df['Description'].str.contains(':')
>>> df[['Machine', 'Action']] = df.loc[has_colon, 'Description'].str.split('\s*:\s*', expand=True)
>>> df
Description Machine Action
0 Machine x : Turn off Machine x Turn off
1 Another action here NaN NaN
2 Another action here NaN NaN
3 Machine y : Turn off Machine y Turn off
4 Machine x : Turn on Machine x Turn on
5 Another action here NaN NaN
如果您更喜歡空字符串,可以NaN通過以下方式替換單元格
>>> df.fillna('')
Description Machine Action
0 Machine x : Turn off Machine x Turn off
1 Another action here
2 Another action here
3 Machine y : Turn off Machine y Turn off
4 Machine x : Turn on Machine x Turn on
5 Another action here
添加回答
舉報