Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning multiple column values in a single row of 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

like image 817
user1204369 Avatar asked Sep 18 '13 21:09

user1204369


People also ask

How do I assign a value to a row in pandas?

You can set cell value of pandas dataframe using df.at[row_label, column_label] = 'Cell Value'. It is the fastest method to set the value of the cell of the pandas dataframe. Dataframe at property of the dataframe allows you to access the single value of the row/column pair using the row and column labels.

How do I assign specific columns in pandas?

You can create a new DataFrame of a specific column by using DataFrame. assign() method. The assign() method assign new columns to a DataFrame, returning a new object (a copy) with the new columns added to the original ones.

How do I convert multiple columns to single column in pandas?

Using pandas. DataFrame. apply() method you can execute a function to a single column, all and list of multiple columns (two or more).


1 Answers

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]
like image 130
Andy Hayden Avatar answered Sep 22 '22 15:09

Andy Hayden