繁体   English   中英

如何将 pandas Dataframe 的索引设置为列长度的索引?

[英]How to set the index of a pandas Dataframe to that of the length of the Columns?

Okay so I have downloaded a sample csv for this from: https://people.sc.fsu.edu/~jburkardt/data/csv/csv.html My questions is this, I have imported a dataframe and indexed out some of the数据。 代码如下所示:

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()

output 是:

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

所以我的问题是现在我已经索引了几个月,DataFrame 索引现在从 3 开始到 6。我怎样才能使索引从 1 开始到 4,尽管使用第二个 DataFrame 的值? 谢谢你!

我对你的问题有点困惑。

但是如果你想重新索引你的 dataframe,你可以这样做:

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

另一种方法:

# 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

Output:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM