Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add array into pandas dataframe

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
like image 857
Filip Eriksson Avatar asked Feb 03 '26 21:02

Filip Eriksson


1 Answers

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
like image 69
Anton Protopopov Avatar answered Feb 06 '26 09:02

Anton Protopopov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!