How to Add Incremental Numbers to a New Column Using Pandas

前端 未结 6 1038
感情败类
感情败类 2020-12-24 04:55

I have this simplified dataframe:

ID   Fruit
F1   Apple
F2   Orange
F3   Banana 

I want to add in the begining of the dataframe a new colum

相关标签:
6条回答
  • 2020-12-24 05:12

    Here:

    df = df.reset_index()
    df.columns[0] = 'New_ID'
    df['New_ID'] = df.index + 880
    
    0 讨论(0)
  • 2020-12-24 05:17
    df = df.assign(New_ID=[880 + i for i in xrange(len(df))])[['New_ID'] + df.columns.tolist()]
    
    >>> df
       New_ID  ID   Fruit
    0     880  F1   Apple
    1     881  F2  Orange
    2     882  F3  Banana
    
    0 讨论(0)
  • 2020-12-24 05:17

    For a pandas DataFrame whose index starts at 0 and increments by 1 (i.e., the default values) you can just do:

    df.insert(0, 'New_ID', df.index + 880)
    

    if you want New_ID to be the first column. Otherwise this if you don't mind it being at the end:

    df['New_ID'] = df.index + 880
    
    0 讨论(0)
  • 2020-12-24 05:22
    df.insert(0, 'New_ID', range(880, 880 + len(df)))
    df
    

    0 讨论(0)
  • 2020-12-24 05:22
    import numpy as np
    
    df['New_ID']=np.arange(880,880+len(df.Fruit))
    df=df.reindex(columns=['New_ID','ID','Fruit'])
    
    0 讨论(0)
  • 2020-12-24 05:30

    You can also simply set your pandas column as list of id values with length same as of dataframe.

    df['New_ID'] = range(880, 880+len(df))
    

    Reference docs : https://pandas.pydata.org/pandas-docs/stable/missing_data.html

    0 讨论(0)
提交回复
热议问题