[英]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. 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数据。 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:现在说我像这样索引第 3 个月到第 7 个月:
import pandas as pd
df = pd.read_csv('/Users/benitocano/Downloads/airtravel.csv')
df = df[3:7]
df.head()
And the output is: 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
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?所以我的问题是现在我已经索引了几个月,DataFrame 索引现在从 3 开始到 6。我怎样才能使索引从 1 开始到 4,尽管使用第二个 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:但是如果你想重新索引你的 dataframe,你可以这样做:
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: 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.