gpt4 book ai didi

python - 如何从我的 DataFrame 中删除 MultiIndex?

转载 作者:行者123 更新时间:2023-12-01 07:11:16 25 4
gpt4 key购买 nike

我尝试使用 df.columns 从数据框中提取列,我得到:

MultiIndex([(     'time', ''),
('numbers', 11),
('numbers', 12),
('numbers', 13),
('numbers', 14)],
names=[None, 'letters'])

我以前从未使用过 MultiIndex,所以我现在很困惑如何将“Time”作为列而不是索引,以便我可以从此 DataFrame 开始:

df = 

time numbers
letters a b c d
0 22:45:00 1016.0 1059.0 1042.0 1007.0
1 23:00:00 1006.0 10507.0 1040.0 1084.0
2 23:15:00 1084.0 1058.0 1047.0 1495.0
3 23:30:00 1095.0 1498.0 1480.0 1048.0
4 23:45:00 1098.0 1002.0 1044.0 1084.0
5 00:00:00 1044.0 1517.0 1084.0 1051.0

(最好只删除 MultiIndex)所以它类似于:

df = 

time a b c d
0 22:45:00 1016.0 1059.0 1042.0 1007.0
1 23:00:00 1006.0 1007.0 1040.0 1084.0
2 23:15:00 1084.0 1058.0 1047.0 1495.0
3 23:30:00 1095.0 1498.0 1480.0 1048.0
4 23:45:00 1098.0 1002.0 1044.0 1084.0
5 00:00:00 1044.0 1517.0 1084.0 1051.0

我尝试过使用 droplevel 但我得到了

Cannot remove 1 levels from an index with 1 levels: at least one level must be left.

这是因为索引位于列而不是行中吗?

最佳答案

IIUC 你有这个:

dd = {('time', ''): {0: '22:45:00',
1: '23:00:00',
2: '23:15:00',
3: '23:30:00',
4: '23:45:00',
5: '00:00:00'},
('numbers', 'a'): {0: 1016.0,
1: 1006.0,
2: 1084.0,
3: 1095.0,
4: 1098.0,
5: 1044.0},
('numbers', 'b'): {0: 1059.0,
1: 10507.0,
2: 1058.0,
3: 1498.0,
4: 1002.0,
5: 1517.0},
('numbers', 'c'): {0: 1042.0,
1: 1040.0,
2: 1047.0,
3: 1480.0,
4: 1044.0,
5: 1084.0},
('numbers', 'd'): {0: 1007.0,
1: 1084.0,
2: 1495.0,
3: 1048.0,
4: 1084.0,
5: 1051.0}}

df1 = pd.DataFrame(dd).rename_axis([None,'letters'], axis=1)
df1

输入数据框:

             time numbers                         
letters a b c d
0 22:45:00 1016.0 1059.0 1042.0 1007.0
1 23:00:00 1006.0 10507.0 1040.0 1084.0
2 23:15:00 1084.0 1058.0 1047.0 1495.0
3 23:30:00 1095.0 1498.0 1480.0 1048.0
4 23:45:00 1098.0 1002.0 1044.0 1084.0
5 00:00:00 1044.0 1517.0 1084.0 1051.0

那么,

df2 = df1.set_index('time')

df2.columns = df2.columns.droplevel(0)

df2.reset_index()

输出:

letters      time       a        b       c       d
0 22:45:00 1016.0 1059.0 1042.0 1007.0
1 23:00:00 1006.0 10507.0 1040.0 1084.0
2 23:15:00 1084.0 1058.0 1047.0 1495.0
3 23:30:00 1095.0 1498.0 1480.0 1048.0
4 23:45:00 1098.0 1002.0 1044.0 1084.0
5 00:00:00 1044.0 1517.0 1084.0 1051.0

关于python - 如何从我的 DataFrame 中删除 MultiIndex?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58209644/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com