pandas :如何将具有多个值的单元格转换为多行? [英] Pandas: how to convert a cell with multiple values to multiple rows?
本文介绍了 pandas :如何将具有多个值的单元格转换为多行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个这样的DataFrame:
I have a DataFrame like this:
Name asn count
Org1 asn1,asn2 1
org2 asn3 2
org3 asn4,asn5 5
我想将我的DataFrame转换成这样:
I would like to convert my DataFrame to look like this:
Name asn count
Org1 asn1 1
Org1 asn2 1
org2 asn3 2
org3 asn4 5
Org3 asn5 5
我知道使用以下代码对两列进行操作,但是我不确定如何对三列进行操作.
I know used the following code to do it with two columns, but I am not sure how can I do it for three.
df2 = df.asn.str.split(',').apply(pd.Series)
df2.index = df.Name
df2 = df2.stack().reset_index('Name')
有人可以帮忙吗?
推荐答案
基于相同的想法,您可以为df2
设置一个MultiIndex,然后进行堆栈.例如:
Carrying on from the same idea, you could set a MultiIndex for df2
and then stack. For example:
>>> df2 = df.asn.str.split(',').apply(pd.Series)
>>> df2.index = df.set_index(['Name', 'count']).index
>>> df2.stack().reset_index(['Name', 'count'])
Name count 0
0 Org1 1 asn1
1 Org1 1 asn2
0 org2 2 asn3
0 org3 5 asn4
1 org3 5 asn5
然后您可以重命名该列并设置您选择的索引.
You can then rename the column and set an index of your choosing.
这篇关于 pandas :如何将具有多个值的单元格转换为多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文