首页 > 解决方案 > 将列表转换为数据框,选择一些特定元素作为列名

问题描述

我有一个清单:

['A1','some text','some text2','B1','some text','some text2,'some text3','A2',
'some text', 'some text2','B2','some text']

我希望将其转换为数据框或字典:

col1(or key)   col2(or value)
A1            'some text','some text2'
B1            'some text','some text2,'some text3'
A2            'some text', 'some text2'
B2            'some text'

IE:

A1,B1,A2,B2 之间的元素应放在不同的列中。

我尝试使用循环并迭代:

for i in range(0,len(list):
    if list[i].startswith('A') or list[i].startswith('B'):
        ### Do something####

这是我想的逻辑。

有没有更好的方法或逻辑来做到这一点?

标签: pythonpandas

解决方案


让我们一步一步来

l=['A1','some text','some text2','B1','some text','some text2','some text3','A2','some text', 'some text2','B2','some text']
df=pd.DataFrame({'col2':l})
df['col1']=df.loc[df.col2.str.startswith(('A','B')), 'col2'] 
# select the column with condition put into another columns
df.col1.ffill(inplace=True)

newdf=df.query('col1!=col2').groupby('col1').col2.agg(','.join)
newdf#you can add reset_index(inplace=True) at the end 
Out[321]: 
col1
A1               some text,some text2
A2               some text,some text2
B1    some text,some text2,some text3
B2                          some text
Name: col2, dtype: object

推荐阅读