3

I have a pandas dataframe called A with one column called "a":

  • date a
  • 2016-01-19 3
  • 2016-01-20: 1
  • 2016-01-21: 2

I have one array that looks like: [4,3,2]. I want to insert this array into the dataframe and give the new column the name b. How do I do that?

Expected output:

  • date a b
  • 2016-01-19 3 4
  • 2016-01-20: 1 3
  • 2016-01-21: 2 2
2
  • 2
    If your list (or your numpy array) and your index have the same length you can do directly something like df['b'] = your_list Commented Jan 21, 2016 at 19:45
  • Then the values for b didn't end up next to a. I guess that was because of the date index. Commented Jan 21, 2016 at 19:46

1 Answer 1

3

As @mgc pointed out in the comment you could do df['b'] = l:

import pandas as pd
from io import StringIO
data="""
    date a
    2016-01-19 3
    2016-01-20 1
    2016-01-21 2
    """
df = pd.read_csv(StringIO(data), sep='\s+')

df = df.set_index('date')
df.index = pd.to_datetime(df.index)

print(df)
            a
date         
2016-01-19  3
2016-01-20  1
2016-01-21  2

l = [4,3,2]

df['b'] = l

print(df)
            a  b
date            
2016-01-19  3  4
2016-01-20  1  3
2016-01-21  2  2
Sign up to request clarification or add additional context in comments.

Comments

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.