想象一下,我有一个这样的熊猫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'
实际上,我想在单独的列中指定组。
答案 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