下面是我的数据框,其中有一列合并在一起
PLUGS\nDESIGN\nGEAR
0 700\nDaewoo 8000 Gearless
1 300\nHyundai 4400 Gearless
2 600\nSTX 2600 Gearless
3 200\nB170 \nGeared
4 362 Wenchong 1700 Mk II \nGeared
5 252\nRichMax 1550 Gearless
6 220\nCV 1100 Plus \nGeared
7 232\nOrskov Mk VII Gearless
8 119\nKouan 1000 Gearless
9 100\nHanjin 700 Gearless
我想把这些列分成三个不同的列,即插头、设计、齿轮。有没有办法做到这一点
下面是我尝试的代码:
new_df[['PLUGS', 'DESIGN', 'GEAR']] = new_df['PLUGS\nDESIGN\nGEAR'].str.split(' ')
print(new_df)
预期产出:
PLUGS DESIGN GEAR
0 700 Daewoo 8000 Gearless
1 300 Hyundai 4400 Gearless
2 600 STX 2600 Gearless
3 200 B170 Geared
4 362 Wenchong 1700 Mk II Geared
5 252 RichMax 1550 Gearless
6 220 CV 1100 Plus Geared
7 232 Orskov Mk VII Gearless
8 119 Kouan 1000 Gearless
9 100 Hanjin 700 Gearless
从数据帧开始:
确实可以在几个分隔符上使用
split
方法,这里是\n
和space
:然后,可以将第一个和最后一个元素分配给正确的列,将其余元素分配给
DESIGN
列:最后一件事是改进
DESIGN
列,使用join
方法将其映射为字符串而不是列表,并删除PLUGS\nDESIGN\nGEAR
列,如下所示:正如评论部分所建议的,正则表达式在这里应该工作得很好
数据帧示例:
只需从列名中删除换行符,即可使可读性易于使用
现在,列名没有任何特殊的汽车:
现在,我们可以使用pandas.Series.str.extract。使用
regex
方法时,所有命名组()
将成为结果中的列名由于,命名组将成为具有预定义名称的列,如
0,1,2
,因此我们可以使用所需名称对它们进行重命名,以获得所需结果,如下所示:结果:
正则表达式解释:
你可以在regex101.com查看
第一个捕获组(\d+)
第二捕获组([^\]+)
第三捕获组([^Gear][a-z]+)
相关问题 更多 >
编程相关推荐