我有以下内容DataFrame
:
import pandas as pd
df = pd.DataFrame({
'col1': ['a, b'],
'col2': [100]
}, index=['A'])
我想要实现的是通过“爆炸”col1
以创建值为col1
2的多级索引-同时保留col2
原始索引的值,例如:
idx_1,idx_2,val
A,a,100
A,b,100
我确定我需要col1.str.split(', ')
在其中,但是我对如何创建所需的结果一无所知-也许我需要一个,pivot_table
但看不到如何获得所需的索引。
我花了一个半小时的时间来研究有关重塑和旋转等方面的文档。我敢肯定,这是直截了当的-我只是不了解找到“正确的东西”所需的术语。
在这里适应第一个答案,这是一种方法。您可能需要使用名称来获得想要的名称。
如果您最终的目标是对非常大的数据帧执行此操作,则可能会有更有效的方法来执行此操作。
import pandas as pd
from pandas import Series
# Create test dataframe
df = pd.DataFrame({'col1': ['a, b'], 'col2': [100]}, index=['A'])
#split the values in column 1 and then stack them up in a big column
s = df.col1.str.split(', ').apply(Series, 1).stack()
# get rid of the last column from the *index* of this stack
# (it was all meaningless numbers if you look at it)
s.index = s.index.droplevel(-1)
# just give it a name - I've picked yours from OP
s.name = 'idx_2'
del df['col1']
df = df.join(s)
# At this point you're more or less there
# If you truly want 'idx_2' as part of the index - do this
indexed_df = df.set_index('idx_2', append=True)
使用原始数据帧作为输入,代码将其作为输出:
>>> indexed_df
col2
idx_2
A a 100
b 100
如果您想给索引指定一些有意义的名称-您可以使用
indexed_df.index.names = ['idx_1','idx_2']
提供输出
col2
idx_1 idx_2
A a 100
b 100
如果您确实希望将索引展平为列,请使用此
indexed_df.reset_index(inplace=True)
提供输出
>>> indexed_df
idx_1 idx_2 col2
0 A a 100
1 A b 100
>>>
如果您尝试一个稍微有趣的示例输入-例如
>>> df = pd.DataFrame({
... 'col1': ['a, b', 'c, d'],
... 'col2': [100,50]
... }, index = ['A','B'])
你滚出去:
>>> indexed_df
col2
idx_2
A a 100
b 100
B c 50
d 50
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句