为什么 python set_index() 会奇怪地改变索引值和列名?

问题描述 投票:0回答:1
df
            date  outbound   inbound
7     2018-08-10  25.25400  21.98596
8     2018-08-11  24.58363  20.37289
9     2018-08-12  26.88802  23.58856
10    2018-08-13  31.69582  27.84120
11    2018-08-14  26.86707  22.79250
...          ...       ...       ...
1829  2023-08-06  27.42222  17.82758
1830  2023-08-07  28.13449  20.50906
1831  2023-08-08  26.09196  20.19482
1832  2023-08-09  22.92866  17.40861
1833  2023-08-10  23.57808  18.21514

[1827 rows x 3 columns]

df.info()

 #   Column       Non-Null Count  Dtype  
---  ------       --------------  -----  
 0   (date,)      1827 non-null   object 
 1   (outbound,)  1827 non-null   float64
 2   (inbound,)   1827 non-null   float64
dtypes: float64(2), object(1)

这就是我的数据框(df)的样子。我不知道为什么列名会显示在我的数据框中没有括号和逗号的情况下。

df.set_index('date', inplace=True)
df

                outbound     inbound
         date       
(2018-08-10,)   25.25400    21.98596
(2018-08-11,)   24.58363    20.37289
(2018-08-12,)   26.88802    23.58856
(2018-08-13,)   31.69582    27.84120
(2018-08-14,)   26.86707    22.79250
... ... ...
(2023-08-06,)   27.42222    17.82758
(2023-08-07,)   28.13449    20.50906
(2023-08-08,)   26.09196    20.19482
(2023-08-09,)   22.92866    17.40861
(2023-08-10,)   23.57808    18.21514
1827 rows × 2 columns

使用 set_index() 后,“日期”的值显示为括号和逗号。

如何解决这个问题?

我使用的是python3.8

似乎没有任何方法可以立即更改和索引中的所有值。 我想编写一个只留下数字和连字符的代码。

python python-3.x dataframe tuples multi-index
1个回答
0
投票

请将索引级别设置为 0,将列转换为常规索引,如下所示:

df.columns = df.columns.get_level_values(0)
df.set_index('date', inplace=True)
© www.soinside.com 2019 - 2024. All rights reserved.