简体   繁体   中英

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 data. The code looks like this:

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

Now say that I index out month 3 to 7 like so:

import pandas as pd

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

And the output is:

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

So my issue is now that I have indexed out the months, the DataFrame index now starts at 3 and goes to 6. How can I make it so that the index starts at 1 and goes to 4, though with the values from the second DataFrame? Thank You!

i am a bit confused with your question.

But if you wish to reindex your dataframe, you coud do something like this:

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

Another approach:

# 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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