Python 如何将选定列的值存储在单独的行中?

Python 如何将选定列的值存储在单独的行中?,python,pandas,dataframe,Python,Pandas,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

我有一个如下所示的数据框:

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)

但我不知道如何从这里继续下去。如何获得所需结果?

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

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

df = df.explode('strc_list')
一个班轮可能看起来像这样:

df.assign(strc_list=df.filter(like='strc', axis=1).apply(list, axis=1)).explode('strc_list')
过滤后,您需要堆栈、droplevel、重命名并连接回df


嗯,我比我更喜欢这个;避免应用和中间列+1:@克莱布:谢谢。你的爆炸也很好。向上投票:+1
df.assign(strc_list=df.filter(like='strc', axis=1).apply(list, axis=1)).explode('strc_list')
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