Pandas adding values into the dataframe

Viewed 47

Here is my code where I'm trying to add/append new values to the third column:

        file = 'excel_name.xlsx'
        df = pd.read_excel(file, engine='openpyxl')
        print(df)
        df.insert(3, 'sub', [1, 7, 4, 1])
        print('test', df)

the output of print(df):

                      name  ...         sub
0                     test1  ...        NaN
1                     test2  ...        NaN
2                     test3  ...        NaN
3                     test4  ...        NaN

What I want to do:

                      name  ...         sub
0                     test1  ...        1
1                     test2  ...        7
2                     test3  ...        4
3                     test4  ...        1
2 Answers

you can do like this:

import pandas as pd
df = pd.read_excel('~/Downloads/excel_name.xlsx')
array = [1,4,7,1]
df['sub'] = array
print(df)

# output
    name  sub
0  test1    1
1  test2    4
2  test3    7
3  test4    1

Warning: Your array and the number of rows in your excel should match.

Edit: Your code also should work, please check the index which you are trying to add, if the last index of the df goes beyond three then it will throw error.

you can use this. This will work for both even and uneven length of list which doesn't match for the length of columns

l = [1,7,4,1]
df.loc[range(len(l)),'sub'] = l
Related