将某些行提升为有序 pandas 数据框中的索引
Promote certain rows to index in an ordered pandas dataframe
我有一个 pandas 数据框,它看起来像:
df=pd.DataFrame(index=['Asia','China','India','Europe','France','Hungary'])
df[2008]=20080
df[2009]=20090
df.loc['Europe']=np.NaN
df.loc['Asia']=np.NaN
print df
2008 2009
Asia NaN NaN
China 20080 20090
India 20080 20090
Europe NaN NaN
France 20080 20090
Hungary 20080 20090
我想 "promote" 欧洲和亚洲成为 MultiIndexes,比它们的组成国家高一个级别以产生:
2008 2009
Asia China 20080 20090
India 20080 20090
Europe France 20080 20090
Hungary 20080 20090
知道这些可提升的行全都是 NaN,这是否可能以一种漂亮的方式实现?
你可以用 cumsum()
:
In [11]: cont = df.isnull().all(1)
In [12]: cont
Out[12]:
Asia True
China False
India False
Europe True
France False
Hungary False
dtype: bool
这使您能够为每一行标记大洲*:
In [13]: continents = df.index[cont][cont.cumsum() - 1]
In [14]: continents
Out[14]: Index([u'Asia', u'Asia', u'Asia', u'Europe', u'Europe', u'Europe'], dtype='object')
In [15]: df.set_index([continents, df.index], inplace=True)
In [16]: df
Out[16]:
2008 2009
Asia Asia NaN NaN
China 20080 20090
India 20080 20090
Europe Europe NaN NaN
France 20080 20090
Hungary 20080 20090
In [17]: df.dropna()
Out[17]:
2008 2009
Asia China 20080 20090
India 20080 20090
Europe France 20080 20090
Hungary 20080 20090
* 注意:不执行此步骤并在 MultiIndex 中设置级别会更有效:
In [21]: res = df.set_index([cont, df.index])
In [21]: res.index = res.index.set_levels(df.index[cont], 0)
此外,您可以在没有 NaN 的情况下构造此(这样您之后就不必删除na)。
注意:在读入数据时(即 construction/concat 期间)执行此操作可能更有效...
我有一个 pandas 数据框,它看起来像:
df=pd.DataFrame(index=['Asia','China','India','Europe','France','Hungary'])
df[2008]=20080
df[2009]=20090
df.loc['Europe']=np.NaN
df.loc['Asia']=np.NaN
print df
2008 2009
Asia NaN NaN
China 20080 20090
India 20080 20090
Europe NaN NaN
France 20080 20090
Hungary 20080 20090
我想 "promote" 欧洲和亚洲成为 MultiIndexes,比它们的组成国家高一个级别以产生:
2008 2009
Asia China 20080 20090
India 20080 20090
Europe France 20080 20090
Hungary 20080 20090
知道这些可提升的行全都是 NaN,这是否可能以一种漂亮的方式实现?
你可以用 cumsum()
:
In [11]: cont = df.isnull().all(1)
In [12]: cont
Out[12]:
Asia True
China False
India False
Europe True
France False
Hungary False
dtype: bool
这使您能够为每一行标记大洲*:
In [13]: continents = df.index[cont][cont.cumsum() - 1]
In [14]: continents
Out[14]: Index([u'Asia', u'Asia', u'Asia', u'Europe', u'Europe', u'Europe'], dtype='object')
In [15]: df.set_index([continents, df.index], inplace=True)
In [16]: df
Out[16]:
2008 2009
Asia Asia NaN NaN
China 20080 20090
India 20080 20090
Europe Europe NaN NaN
France 20080 20090
Hungary 20080 20090
In [17]: df.dropna()
Out[17]:
2008 2009
Asia China 20080 20090
India 20080 20090
Europe France 20080 20090
Hungary 20080 20090
* 注意:不执行此步骤并在 MultiIndex 中设置级别会更有效:
In [21]: res = df.set_index([cont, df.index])
In [21]: res.index = res.index.set_levels(df.index[cont], 0)
此外,您可以在没有 NaN 的情况下构造此(这样您之后就不必删除na)。
注意:在读入数据时(即 construction/concat 期间)执行此操作可能更有效...