如何将数据帧的索引设置为列长度的索引?

2024-09-26 22:49:21 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,我从以下网站下载了一个csv示例: https://people.sc.fsu.edu/~jburkardt/data/csv/csv.html 我的问题是,我已经导入了一个数据帧并索引出了一些数据。代码如下所示:

import pandas as pd

df = pd.read_csv('/Users/benitocano/Downloads/airtravel.csv')

df.head()
And the output is:
    Month   "1958"  "1959"  "1960"
0   JAN 340 360 417
1   FEB 318 342 391
2   MAR 362 406 419
3   APR 348 396 461
4   MAY 363 420 472

现在,假设我将第3个月索引到第7个月,如下所示:

import pandas as pd

df = pd.read_csv('/Users/benitocano/Downloads/airtravel.csv')
df = df[3:7]
df.head()

输出为:

    Month "1958" "1959" "1960"
3   APR  348     396     461
4   MAY  363     420     472
5   JUN  435     472     535
6   JUL  491     548     622

所以我的问题是,现在我已经索引了月份,数据帧索引现在从3开始,到6。如何使索引从1开始到4,尽管使用第二个数据帧中的值?谢谢大家!


Tags: csv数据importpandasdfreaddownloadsas
2条回答

另一种方法:

# Subsection of original dataframe
df2 = df[3:7]

# Set index to new index values plus 1
df2.index = df2.reset_index(drop=True).index + 1

输出:

  Month   "1958"   "1959"   "1960"
1   APR      348      396      461
2   MAY      363      420      472
3   JUN      435      472      535
4   JUL      491      548      622

我对你的问题有点困惑

但是,如果您希望对数据帧重新编制索引,可以执行以下操作:

df.index = range(1, 5) # or replace 5 with df.shape[0]+1

相关问题 更多 >

    热门问题