将一个系列分配给 Pandas DataFrame 的几行 [英] Assign a Series to several Rows of a Pandas DataFrame
问题描述
我有一个用索引和列准备的 Pandas DataFrame,所有值都是 NaN.现在我计算了一个结果,它可以用于一个以上的 DataFrame 行,我想一次分配它们.这可以通过一个循环来完成,但我很确定这个任务可以一次完成.
I have a pandas DataFrame prepared with an Index and columns, all values are NaN. Now I computed a result, which can be used for more than one row of a DataFrame, and I would like to assign them all at once. This can be done by a loop, but I am pretty sure that this assignment can be done at once.
这是一个场景:
import pandas as pd
df = pd.DataFrame(index=['A', 'B', 'C'], columns=['C1', 'C2']) # original df
s = pd.Series({'C1': 1, 'C2': 'ham'}) # a computed result
index = pd.Index(['A', 'C']) # result is valid for rows 'A' and 'C'
幼稚的方法是
df.loc[index, :] = s
但这根本不会改变DataFrame.它仍然是
But this does not change the DataFrame at all. It remains as
C1 C2
A NaN NaN
B NaN NaN
C NaN NaN
如何完成这项任务?
推荐答案
看来可以用底层数组数据来赋值了-
It seems we can use the underlying array data to assign -
df.loc[index, :] = s.values
现在,这里假设 s
中的索引顺序与 df
的列中的索引顺序相同.如果不是这种情况,如 @Nras 建议
,我们可以使用 s[df.columns].values
进行右侧赋值.
Now, this assumes that the order of index in s
is same as in the columns of df
. If that's not the case, as suggested by @Nras
, we could use s[df.columns].values
for right side assignment.
这篇关于将一个系列分配给 Pandas DataFrame 的几行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!