Python Pandas: Assign numpy array to a part of dataframe

Viewed 1811

lets say I have a dataframe like this:

 A    B     C 
 1   NaN   NaN 
 2   NaN   NaN 

And I have a numpy array like this np_array = ['ab', 'bc'], I want to make this array as a part of the dataframe rows like this:

 A    B      C 
 1   'ab'   'bc'
 2   NaN     NaN 

How can I do this most efficiently. Thanks=)

2 Answers

Try below solution:

import pandas as pd
import numpy as np

dic = {'A': [1, 2], 'B': [None, None], 'C': [None, None]}
np_array = np.array(['ab', 'bc'])
df = pd.DataFrame(dic)

print(df)

#Method 1
df.iloc[0, 1:] = np_array
print(df)

#Medthod 2

df = pd.DataFrame(dic)
df.loc[0, ['B', 'C']] = np_array
print(df)

Output

   A     B     C
0  1  None  None
1  2  None  None

   A     B     C
0  1    ab    bc
1  2  None  None

Name: 0, dtype: object

   A     B     C
0  1    ab    bc
1  2  None  None

This can be done with:

df.iloc[row] = np_array

where row is the 0-indexed row you want to change

Related