4

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=)

3
  • df.loc[df['A'].eq(1), ['B','C']] = np_array Commented Mar 13, 2020 at 8:43
  • 1
    or maybe: df.iloc[0, 1:] = np_array... Commented Mar 13, 2020 at 8:44
  • or maybe: df.fillna({c:v for c,v in zip(df.columns, np_array)}, limit=1) Commented Mar 13, 2020 at 8:45

2 Answers 2

1

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

Comments

0

This can be done with:

df.iloc[row] = np_array

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

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.