我正在尝试将多个值分配给DataFrame中的单个行,我需要正确的语法。
请参阅下面的代码。
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]
感谢您的帮助
答案 0 :(得分:22)
使用loc
(并避免链接):
In [11]: df.loc[3] = ['V1', 4.3, 2.2, 2.2, 20.2]
这可确保分配在DataFrame上完成,而不是在副本上完成(并收集垃圾)。
您只能指定某些列:
In [12]: df.loc[3, list('ABCDE')] = ['V1', 4.3, 2.2, 2.2, 20.2]