![](/img/trans.png)
[英]How does one determine which columns to set as an index in a 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.