python - 将列表转换为数据框,选择一些特定元素作为列名
问题描述
我有一个清单:
['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####
这是我想的逻辑。
有没有更好的方法或逻辑来做到这一点?
解决方案
让我们一步一步来
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
推荐阅读
- regex - 想使用 Bash & Regex 替换文件中的逗号
- laravel - Laravel:如何使用 Simple QrCode 生成与图像合并的 QR 码
- sql - 一步删除子表和父表中的行
- pytorch - RuntimeError:意外的 EOF,预计多 3302200 个字节。文件可能已损坏
- reactjs - 使用 map 方法中的 react-router-dom 创建路由,但它不会重定向到 JSX 组件
- c++ - 如何在 Code::Blocks 中修复 Google Test 的构建错误?
- python - 如何按文件扩展名类型列表过滤s3 boto过滤对象
- flask - 如何限制对一个选项卡的访问以防止合并冲突
- sql-server - 当分配的空间阻止您这样做时,更改 Azure SQL 数据库层的最佳方法是什么?
- gijgo-treeview - 如何在树视图中限制儿童深度