熊猫 - 在某些单元格中拆分字符串

2024-04-27 04:10:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列,其中一些单元格有多个值,我想拆分它们,因此它们会进入一个新行。在

这是我的数据框中的一个示例:

        index   ref_made_call
0   58  Sean Wright
1   115 Nick Buchert
2   191 James Williams
3   196 Jason Phillips
4   266 Scott Wall
5   272 Curtis Blair
6   390 Bennett Salvatore
7   490 Derrick Stafford
8   600 Kevin Cutler
9   683 Josh Tiven
10  816 Bennett Salvatore
11  1014    Joe Crawford
12  1255    Scott Foster,Sean Wright

我想拆分Scott Foster,Sean Wright,这样数据帧看起来像:

^{pr2}$

我已经看过了this,但它不能满足我的需要。在

谢谢你的帮助!在


Tags: 数据ref示例indexcallscottnickbennett
1条回答
网友
1楼 · 发布于 2024-04-27 04:10:45

使用str.split+stack

df.set_index('index') \
    .ref_made_call.str.split(',', expand=True) \
    .stack().reset_index(-1, drop=True) \
    .reset_index(name='ref_made_call')

    index      ref_made_call
0      58        Sean Wright
1     115       Nick Buchert
2     191     James Williams
3     196     Jason Phillips
4     266         Scott Wall
5     272       Curtis Blair
6     390  Bennett Salvatore
7     490   Derrick Stafford
8     600       Kevin Cutler
9     683         Josh Tiven
10    816  Bennett Salvatore
11   1014       Joe Crawford
12   1255       Scott Foster
13   1255        Sean Wright

相关问题 更多 >