如何将所选列的值存储在单独的行中



我有一个DataFrame,如下所示:

import pandas as pd
df = pd.DataFrame({
'ids': range(4),
'strc': ['some', 'thing', 'abc', 'foo'],
'not_relevant': range(4),
'strc2': list('abcd'),
'strc3': list('lkjh')
})
ids   strc  not_relevant strc2 strc3
0    0   some             0     a     l
1    1  thing             1     b     k
2    2    abc             2     c     j
3    3    foo             3     d     h

对于ids中的每个值,我希望收集存储在以strc开头的列,并将它们放在一个名为strc_list的单独列中,所以我想要:

ids   strc  not_relevant strc2 strc3 strc_list
0    0   some             0     a     l      some
0    0   some             0     a     l         a
0    0   some             0     a     l         l
1    1  thing             1     b     k     thing
1    1  thing             1     b     k         b
1    1  thing             1     b     k         k
2    2    abc             2     c     j       abc
2    2    abc             2     c     j         c
2    2    abc             2     c     j         j
3    3    foo             3     d     h       foo
3    3    foo             3     d     h         d
3    3    foo             3     d     h         h

我知道我可以使用选择所有需要的列

df.filter(like='strc', axis=1)

但我不知道如何从这里继续。我怎样才能得到我想要的结果?

filter之后,您需要stackdroplevelrenamejoin返回df

df1 = df.join(df.filter(like='strc', axis=1).stack().droplevel(1).rename('strc_list'))
Out[135]:
ids   strc  not_relevant strc2 strc3 strc_list
0    0   some             0     a     l      some
0    0   some             0     a     l         a
0    0   some             0     a     l         l
1    1  thing             1     b     k     thing
1    1  thing             1     b     k         b
1    1  thing             1     b     k         k
2    2    abc             2     c     j       abc
2    2    abc             2     c     j         c
2    2    abc             2     c     j         j
3    3    foo             3     d     h       foo
3    3    foo             3     d     h         d
3    3    foo             3     d     h         h

您可以首先使用apply:将所需值存储在列表中

df['strc_list'] = df.filter(like='strc', axis=1).apply(list, axis=1)
0     [some, a, l]
1    [thing, b, k]
2      [abc, c, j]
3      [foo, d, h]

然后使用explode将它们分布在单独的行上:

df = df.explode('strc_list')

一条直线可能看起来像这样:

df.assign(strc_list=df.filter(like='strc', axis=1).apply(list, axis=1)).explode('strc_list')

最新更新