1

I would like to add a numpy array to each row in my dataframe: I do have a dataframe holdings some data in each row and now i like to add a new column which contains an n element array.

for example:

Name, Years
 Test, 2
 Test2, 4

Now i like to add:

testarray1 = [100, 101, 1 , 0, 0, 5] as a new column='array' to Name='Test'

Name, Years, array
 Test, 2, testarray1
 Test2, 4, NaN

how can i do this ?

quant
  • 33
  • 3

2 Answers2

0

Try this

import pandas as pd
import numpy as np
df = pd.DataFrame({'name':['test', 'test2'], 'year':[1,2]})
print(df)

x = np.arange(5)
df['array']=[x,np.nan]
print(df)
James Fulton
  • 322
  • 2
  • 8
0
import pandas as pd
import numpy as np

testarray1 = [100, 101, 1 , 0, 0, 5]

d = {'Name':['Test', 'Test2'], 
     'Years': [2, 4]
    }

df = pd.DataFrame(d)  # create a DataFrame of the data
df.set_index('Name', inplace=True)  # set the 'Name' column as the dataframe index

df['array'] = np.NaN  # create a new empty 'array' column (filled with NaNs)
df['array'] = df['array'].astype(object)  # convert it to an 'object' data type

df.at['Test', 'array'] = testarray1  # fill in the cell where index equals 'Test' and column equals 'array'

df.reset_index(inplace=True)  # if you don't want 'Name' to be the dataframe index

print(df)

    Name  Years                   array
0   Test      2  [100, 101, 1, 0, 0, 5]
1  Test2      4                     NaN
Matt
  • 972
  • 3
  • 11
  • 22