【发布时间】:2021-07-21 01:40:57
【问题描述】:
我有一个如下所示的 pandas 数据框:
ID Col.A
28654 This is a dark chocolate which is sweet
39876 Sky is blue 1234 Sky is cloudy 3423
88776 Stars can be seen in the dark sky
35491 Schools are closed 4568 but shops are open
我试图在 dark 或 digits 之前拆分 Col.A。我想要的结果如下所示。
ID Col.A Col.B
28654 This is a dark chocolate which is sweet
39876 Sky is blue 1234 Sky is cloudy 3423
88776 Stars can be seen in the dark sky
35491 Schools are closed 4568 but shops are open
我尝试将包含单词dark 的行分组到一个数据帧,并将带有数字的行分组到另一个数据帧,然后相应地拆分它们。之后,我可以连接生成的数据帧以获得预期的结果。代码如下:
df = pd.DataFrame({'ID':[28654,39876,88776,35491], 'Col.A':['This is a dark chocolate which is sweet',
'Sky is blue 1234 Sky is cloudy 3423',
'Stars can be seen in the dark sky',
'Schools are closed 4568 but shops are open']})
df1 = df[df['Col.A'].str.contains(' dark ')==True]
df2 = df.merge(df1,indicator = True, how='left').loc[lambda x : x['_merge']!='both']
df1 = df1["Col.A"].str.split(' dark ', expand = True)
df2 = df2["Col.A"].str.split('\d+', expand = True)
pd.concat([[df1, df2], axis =0)
得到的结果与预期的不同。也就是说,
0 1
0 This is a chocolate which is sweet
2 Stars can be seen in the sky
1 Sky is blue Sky is cloudy
3 Schools are closed but shops are open
我错过了字符串中的数字和结果中的单词dark。
那么我怎样才能解决这个问题并在不丢失拆分单词和数字的情况下获得结果呢?
有没有办法“在预期的单词或数字之前切片”而不删除它们?
【问题讨论】:
标签: python regex pandas dataframe