user1204369 user1204369 -4 years ago 238
Python Question

Assigning multiple column values to a python pandas DataFrame in one line

I'm trying to Assign multiple values to a single row in a DataFrame and I need the correct syntax.

See the code below.

import pandas as pd

df = pd.DataFrame({
'A': range(10),
'B' : '',
'C' : 0.0,
'D' : 0.0,
'E': 0.0,
})

#Works fine
df['A'][2] = 'tst'

#Is there a way to assign multiple values in a single line and if so what is the correct syntax
df[['A', 'B', 'C', 'D', 'E']][3] = ['V1', 4.3, 2.2, 2.2, 20.2]


Thanks for the help

Answer Source

Use loc (and avoid chaining):

In [11]: df.loc[3] = ['V1', 4.3, 2.2, 2.2, 20.2]

This ensures the assigning is done inplace on the DataFrame, rather than on a copy (and garbage collected).

You can specify only certain columns:

 In [12]: df.loc[3, list('ABCDE')] = ['V1', 4.3, 2.2, 2.2, 20.2]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download