用系列更新数据帧

kek*_*ert 6 python dataframe pandas

有一个数据帧,我想更新列的子集,其长度与正在更新的列数相同:

>>> df = pd.DataFrame(np.random.randint(0,5,(6, 2)), columns=['col1','col2'])
>>> df

   col1  col2
0     1     0
1     2     4
2     4     4
3     4     0
4     0     0
5     3     1

>>> df.loc[:,['col1','col2']] = pd.Series([0,1])
...
ValueError: shape mismatch: value array of shape (6,) could not be broadcast to indexing result of shape (2,6)
Run Code Online (Sandbox Code Playgroud)

然而,它失败了,我可以使用list做同样的事情:

>>> df.loc[:,['col1','col2']] = list(pd.Series([0,1]))
>>> df
   col1  col2
0     0     1
1     0     1
2     0     1
3     0     1
4     0     1
5     0     1
Run Code Online (Sandbox Code Playgroud)

你能帮我理解,为什么系列更新失败了?我必须进行一些特殊的重塑吗?

piR*_*red 4

当使用 pandas 对象进行赋值时,pandas 会更加“严格”地对待赋值。pandas 到 pandas 的分配必须通过更严格的协议。只有当你把它变成一个列表(或等效的pd.Series([0, 1]).values)时,pandas 才会屈服并允许你按照你想象的方式进行分配。

更高的分配标准要求索引也对齐,因此即使您具有正确的形状,如果没有正确的索引,它仍然无法工作。

df.loc[:, ['col1', 'col2']] = pd.DataFrame([[0, 1] for _ in range(6)])
df
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

df.loc[:, ['col1', 'col2']] = pd.DataFrame([[0, 1] for _ in range(6)], columns=['col1', 'col2'])
df
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

  • 也许需要进行一些检查,因为如果只有 2 行,它会很好地工作 - `df = pd.DataFrame(np.random.randint(0,5,(2, 2)), columns=['col1',' col2'])`, `df.loc[:,['col1','col2']] = pd.Series([0,1])` +1 (2认同)