2

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
4
  • Does your output come from the first print statement or the second? Commented Jul 15, 2022 at 9:32
  • The first one. I want to make look like the second one Commented Jul 15, 2022 at 9:37
  • Just assign mylist = [1,7,4,1] then df['sub'] = mylist Commented Jul 15, 2022 at 9:37
  • Please check out this solution : stackoverflow.com/a/51561012/8352083 Commented Jul 15, 2022 at 9:41

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

2 Comments

What's the solution if these two don't match?
you have two solution, if you want to join across proper key, then you can use pandas join and second solution is, if you want the value to be sequentially added in the dataframe, then create array with null elements on the remaining value and use the above method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.