Christy
Christy

Reputation: 58

Pandas dataframe, how to set multiple column values in a single row?

for example:

import pandas as pd

df_1 = pd.DataFrame({"A":[1, 5, 3, 4, 2], 
                   "B":[3, 2, 4, 3, 4],  
                   "C":[2, 2, 7, 3, 4],  
                   "D":[4, 3, 6, 12, 7]})
df_2 = pd.DataFrame(index = list(range(5)),columns = ['a','c'])
df_2.loc[2,['a','c']] = df_1.loc[2,['A','C']]
print(df_1.loc[2,['A','C']])
print(df_2)

I got:

A    3 
C    7 
Name: 2, dtype: int64

     a    c 

0  NaN  NaN 
1  NaN  NaN 
2  NaN  NaN 
3  NaN  NaN 
4  NaN  NaN

Obviously I failed to set multiple cells at the same time in one row. Is there any way to achieve this? (except using loops)

Upvotes: 2

Views: 1316

Answers (1)

jezrael
jezrael

Reputation: 862681

Here working index alignment, so because different a, c with A, C columns it set missing values (here not change), solution is set by numpy array for avoid it:

df_2.loc[2,['a','c']] = df_1.loc[2,['A','C']].values
print (df_2)
     a    c
0  NaN  NaN
1  NaN  NaN
2    3    7
3  NaN  NaN
4  NaN  NaN

If replace columns names for match, it working nice:

df_2.loc[2,['a','c']] = df_1.loc[2,['A','C']].rename({'A':'a','C':'c'})
#alternative
#df_2.loc[2,['a','c']] = df_1.rename(columns={'A':'a','C':'c'}).loc[2,['a','c']]

print (df_2)
     a    c
0  NaN  NaN
1  NaN  NaN
2    3    7
3  NaN  NaN
4  NaN  NaN

Upvotes: 4

Related Questions