python:基于列名条件创建一个多索引pandas DF



我有一个数据框架如下:

arrays = [np.array(["berlin", "berlin", "paris", "paris", "rome", "rome", "seville", "seville"]),
np.array(["one", "two", "one", "two", "one", "two", "one", "two"])]
df = pd.DataFrame(np.random.randn(8, 4), index=arrays, columns = ['mike','ana','manu','analia'])

在行中有一个多索引。我想把这个DF转换成另一个在列中也有一个多索引的DF。

函数可以概括为:

def sortit(colname):
if colname.startswith('m'):
return 'm'
elif colname.startswith('m'): 
return 'a'

预期输出如下:

arrays = [np.array(["berlin", "berlin", "paris", "paris", "rome", "rome", "seville", "seville"]),
np.array(["one", "two", "one", "two", "one", "two", "one", "two"])]
tuples_i = list(zip(*arrays))
index_rows = pd.MultiIndex.from_tuples(tuples_i, names=["city", "number"])
arrays2 = [np.array(["m","m", "a","a"]),
np.array(['mike','manu','ana','analia'])]
tuples_c = list(zip(*arrays2))
print(tuples)
index_columns = pd.MultiIndex.from_tuples(tuples_c, names=["department", "name"])
df = pd.DataFrame(np.random.randn(8, 4), index=index_rows, columns = index_columns)
df

两个重要的注意事项。

我的起始点是行中有多个索引而cols中没有多个索引的数据框。我不能改变这一点。

这里的方法说明了多索引属于每个名称(列名)是一个直接的一个,作为例子,现实是,这个函数是更复杂和耗时的方式,这就是为什么我想创建一次多级col索引,使查询更快。

你可以用MultiIndex.from_arrays:

创建一个新的MultiIndex
idx = pd.MultiIndex.from_arrays([df.columns.str.extract('(.)', expand=False),
df.columns],
names=['department', 'name'])
df.columns = idx
print(df.sort_index(level=0, axis=1))

输出:

department          a                   m          
name              ana    analia      manu      mike
berlin  one  0.465270 -0.549246  0.931020  0.027496
two -2.156006 -2.053703  0.162281  0.741966
paris   one  0.084072  1.729949  1.366554  0.402933
two  1.157244  1.762093 -1.808943 -1.737110
rome    one -0.009257 -0.457297 -0.479836 -2.483149
two -0.593379 -0.012763 -1.491018 -0.439712
seville one -1.118433  0.029189 -0.805858 -0.342481
two -0.389120 -0.390189 -1.260496 -0.010572

Code

你可以通过创建元组轻松地创建多索引

(df.set_axis(df.columns.map(lambda x: (x[0], x)), axis=1)
.rename_axis(['department', 'name'], axis=1))

输出:

department  m       a       m       a
name        mike    ana     manu    analia
berlin  one 0.6     -0.0    2.9     1.3
two 1.3     0.4     0.0     -3.0
paris   one -0.5    -0.8    0.4     0.0
two -0.6    -1.0    0.5     0.3
rome    one -1.5    0.2     -0.0    1.4
two -1.5    -1.9    0.0     -0.0
seville one -1.3    1.3     0.7     0.5
two -0.2    -0.2    -0.7    0.4

相关内容

最新更新