【问题标题】:How to set the index of a pandas Dataframe to that of the length of the Columns?如何将熊猫数据框的索引设置为列的长度?
【发布时间】:2021-01-02 03:31:14
【问题描述】:

好的,我已经从以下位置下载了一个示例 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

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

【问题讨论】:

    标签: python pandas dataframe indexing


    【解决方案1】:

    我对你的问题有点困惑。

    但如果你想重新索引你的数据框,你可以这样做:

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

    【讨论】:

    • 对混乱感到抱歉,但这确实对我有所帮助...我不知道可以将索引定义为类似于变量,因为尽管使用 d.set_index 对此我感到厌烦。非常感谢,新年快乐
    【解决方案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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-26
      相关资源
      最近更新 更多