从pandas数据框的一列中提取组标题作为separte列

时间:2020-06-24 16:04:39

标签: python pandas

想象一下,我有一个这样的熊猫df:

0 'A'
1 'some text'
2 'more text'
3 'B'
4 'hello'
5 'hi'

我还有一个列表= ['A', 'B'],其中包含每个组的标题...

...而且我想将df转换成这样:

0 'A' 'some text'
1 'A' 'more text'
2 'B' 'hello'
3 'B' 'hi'

实际上,我想在单独的列中指定组。

1 个答案:

答案 0 :(得分:2)

您可以先执行mask,然后执行ffill来提取组:

s = ~df['str'].isin(lst)

df['group'] = df['str'].mask(s).ffill()
df = df[s]

输出:

   idx        str group
1    1  some text     A
2    2  more text     A
4    4      hello     B
5    5         hi     B