I have the following DataFrame data
with random index values:
A B 100 0 7 203 5 4 5992 0 10 2003 9 8 20 10 5 12 6 2
I would like to add a new column 'C' with row numbers. For example:
A B C 100 0 7 0 203 5 4 1 5992 0 10 2 2003 9 8 3 20 10 5 4 12 6 2 5
You can use the assign() function to add a new column to the end of a pandas DataFrame: df = df. assign(col_name=[value1, value2, value3, ...])
Generate row number in pandas using index() function In order to generate the row number in pandas we can also use index() function. dataframe. index() function generates the row number.
Fill Data in an Empty Pandas DataFrame by Appending Rows First, create an empty DataFrame with column names and then append rows one by one. The append() method can also append rows. When creating an empty DataFrame with column names and row indices, we can fill data in rows using the loc() method.
Use numpy.arange
by length of DataFrame
:
df['C'] = np.arange(len(df))
Or you can use DataFrame.shape
, thank you @Mehmet Burak Sayıcı:
df['C'] = np.arange(df.shape[0])
print (df) A B C 100 0 7 0 203 5 4 1 5992 0 10 2 2003 9 8 3 20 10 5 4 12 6 2 5
By using reset_index
df['C'] = df.reset_index().index df A B C 100 0 7 0 203 5 4 1 5992 0 10 2 2003 9 8 3 20 10 5 4 12 6 2 5
To generalise:
df['C'] = df.index if df.index.is_monotonic_increasing else range(len(df)) df A B C 100 0 7 0 203 5 4 1 5992 0 10 2 2003 9 8 3 20 10 5 4 12 6 2 5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With