将包含元素列表的列展开为字符串

2024-07-01 07:53:57 发布

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

我的问题与此类似:

pandas: When cell contents are lists, create a row for each element in the list

我想为samples中列表的每个元素创建重复的行,但现在这些元素存储为单个字符串,类似于:

                   samples  subject  trial_num
0    '[string1, string21, string3]'        1          1
1    '[string3, string24, string3]'        1          2
2    '[string4, string24, string4]'        1          3
3    '[string5, string24, string5]'        2          1
4    '[string13, string24, string6]'        2          2
5    '[string16, string24, string6]'        2          3

谢谢


Tags: 元素pandascreatecontentscellarelistsrow
1条回答
网友
1楼 · 发布于 2024-07-01 07:53:57
from ast import literal_eval

df.assign(samples=df.samples.str.strip("'").apply(literal_eval)).pipe(
    lambda d: d.loc[d.index.repeat(d.samples.str.len())].assign(
        samples=np.concatenate(d.samples)
    )
)

   samples  subject  trial_num
0     0.57        1          1
0    -0.83        1          1
0     1.44        1          1
1    -0.01        1          2
1     1.13        1          2
1     0.36        1          2
2     1.18        1          3
2    -1.46        1          3
2    -0.94        1          3
3    -0.08        2          1
3    -4.22        2          1
3    -2.05        2          1
4     0.72        2          2
4     0.79        2          2
4     0.53        2          2
5     0.40        2          3
5    -0.32        2          3
5    -0.13        2          3

相关问题 更多 >

    热门问题