pandas 在一行中分配一行pandas DataFrame中的多个列值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18882501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:09:54  来源:igfitidea点击:

Assigning multiple column values in a single row of pandas DataFrame, in one line

pythonpandasdataframe

提问by user1204369

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

我正在尝试为 DataFrame 中的一行分配多个值,我需要正确的语法。

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

谢谢您的帮助

回答by Andy Hayden

Use loc(and avoid chaining):

使用loc(并避免链接):

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

这确保分配在 DataFrame 上就地完成,而不是在副本(和垃圾收集)上完成。

You can specify only certain columns:

您只能指定某些列:

 In [12]: df.loc[3, list('ABCDE')] = ['V1', 4.3, 2.2, 2.2, 20.2]