Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
475 views
in Technique[技术] by (71.8m points)

python - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...