Pandas: Adding new column to dataframe which is a copy of the index column

后端 未结 2 538
花落未央
花落未央 2020-11-22 05:41

I have a dataframe which I want to plot with matplotlib, but the index column is the time and I cannot plot it.

This is the dataframe (df3):

but whe

2条回答
  •  孤城傲影
    2020-11-22 06:20

    I think you need reset_index:

    df3 = df3.reset_index()
    

    Possible solution, but I think inplace is not good practice, check this and this:

    df3.reset_index(inplace=True)
    

    But if you need new column, use:

    df3['new'] = df3.index
    

    I think you can read_csv better:

    df = pd.read_csv('university2.csv', 
                     sep=";", 
                     skiprows=1,
                     index_col='YYYY-MO-DD HH-MI-SS_SSS',
                     parse_dates='YYYY-MO-DD HH-MI-SS_SSS') #if doesnt work, use pd.to_datetime
    

    And then omit:

    #Changing datetime
    df['YYYY-MO-DD HH-MI-SS_SSS'] = pd.to_datetime(df['YYYY-MO-DD HH-MI-SS_SSS'], 
                                                   format='%Y-%m-%d %H:%M:%S:%f')
    #Set index from column
    df = df.set_index('YYYY-MO-DD HH-MI-SS_SSS')
    

提交回复
热议问题