我有一个熊猫数据框,它具有以下列:
n_0
n_1
p_0
p_1
e_0
e_1
我想将其转换为具有列和子列:
0
n
p
e
1
n
p
e
我已经在文档中进行了搜索,但我完全不知道如何实现这一点。有没有人有什么建议?
我有一个熊猫数据框,它具有以下列:
n_0
n_1
p_0
p_1
e_0
e_1
我想将其转换为具有列和子列:
0
n
p
e
1
n
p
e
我已经在文档中进行了搜索,但我完全不知道如何实现这一点。有没有人有什么建议?
columns=[('0', 'n'), ('0', 'p'), ('0', 'e'), ('1', 'n'), ('1', 'p'), ('1', 'e')]
df.columns = pd.MultiIndex.from_tuples(columns)
最后,我找到了解决方案。
您可以在下面找到示例脚本。
#!/usr/bin/env python3
import pickle
import pandas as pd
import itertools
import numpy as np
data = pd.DataFrame(np.random.randn(10, 5), columns=('0_n', '1_n', '0_p', '1_p', 'x'))
indices = set()
groups = set()
others = set()
for c in data.columns:
if '_' in c:
(i, g) = c.split('_')
c2 = pd.MultiIndex.from_tuples((i, g),)
indices.add(int(i))
groups.add(g)
else:
others.add(c)
columns = list(itertools.product(groups, indices))
columns = pd.MultiIndex.from_tuples(columns)
ret = pd.DataFrame(columns=columns)
for c in columns:
ret[c] = data['%d_%s' % (int(c[1]), c[0])]
for c in others:
ret[c] = data['%s' % c]
ret.rename(columns={'total': 'total_indices'}, inplace=True)
print("Before:")
print(data)
print("")
print("After:")
print(ret)
非常遗憾...
我不得不调整 victor 的排序以获得 OP 的特定列格式:
df = df.sort_index(level=0, axis=1)
0 1
e n p e n p
0 -0.995452 -3.237846 1.298927 -0.269253 -0.857724 -0.461103```
有一个更简单的解决方案:
data.columns = data.columns.str.split('_', expand=True)
要排列列名,还可以这样做:
data.sort_index(axis=1, inplace=True)
要更改列级别:
data = data.reorder_levels([1,0], axis=1)