gpt4 book ai didi

python - 摆脱 Pandas 中的分层索引

转载 作者:行者123 更新时间:2023-12-01 05:34:14 24 4
gpt4 key购买 nike

我刚刚旋转了一个数据框来创建下面的数据框:

date       2012-10-31   2012-11-30
term
red -4.043862 -0.709225
blue -18.046630 -8.137812
green -8.339924 -6.358016

这些列应该是日期,最左边的列应该包含字符串。

我希望能够遍历行(使用 .apply())并比较每个日期列下的值。我遇到的问题是我认为 df 有一个分层索引。

有没有办法给整个 df 一个新的索引(例如 1、2、3 等),然后有一个平坦的索引(但不去掉第一列中的术语)?

编辑:当我尝试使用 .reset_index() 时,出现以“AttributeError: 'str' object has no attribute 'view'' 结尾的错误。

编辑2:这就是 df 的样子:

enter image description here

编辑3:这是 df 的描述:

<class 'pandas.core.frame.DataFrame'>
Index: 14597 entries, 101016j to zymogens
Data columns (total 6 columns):
2012-10-31 00:00:00 14597 non-null values
2012-11-30 00:00:00 14597 non-null values
2012-12-31 00:00:00 14597 non-null values
2013-01-31 00:00:00 14597 non-null values
2013-02-28 00:00:00 14597 non-null values
2013-03-31 00:00:00 14597 non-null values
dtypes: float64(6)

提前致谢。

最佳答案

df= df.reset_index()

这将获取当前索引并将其设为一列,然后为您提供从 0 开始的新索引

添加示例:

import pandas as pd
import numpy as np
df = pd.DataFrame({'2012-10-31': [-4, -18, -18], '2012-11-30': [-0.7, -8, -6]}, index = ['red', 'blue','green'])

df
2012-10-31 2012-11-30
red -4 -0.7
blue -18 -8.0
green -18 -6.0

df.reset_index()
term 2012-10-31 2012-11-30
0 red -4 -0.7
1 blue -18 -8.0
2 green -18 -6.0

关于python - 摆脱 Pandas 中的分层索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19478112/

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