python - 如何将值中带有列表的数据框转换为每个级别作为单列值的大数据框? [英] how to convert a data frame with a list in the value to a big data frame with the each level as a single column value in python?
本文介绍了python - 如何将值中带有列表的数据框转换为每个级别作为单列值的大数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个如下所示的数据框:
I have a data frame look like below:
mydata = [{'col_A' : 'A', 'col_B': [1,2,3]},
{'col_A' : 'B', 'col_B': [7,8]}]
pd.DataFrame(mydata)
col_A col_B
A [1, 2, 3]
B [7, 8]
如何拆分列表中的值并创建如下所示的数据框:
How to split the value in the list and create a data frame that look like this:
col_A col_B
A 1
A 2
A 3
B 7
B 8
推荐答案
试试这个:
pd.DataFrame([{'col_A':row['col_A'], 'col_B':val}
for ind, row in df.iterrows()
for val in row['col_B']])
您也许还可以使用 apply() 函数做一些聪明的事情,但我脑子里想不出怎么做.
You might also be able to do something clever with the apply() function, but off the top of my head, I can think of how.
这篇关于python - 如何将值中带有列表的数据框转换为每个级别作为单列值的大数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文