![](/img/trans.png)
[英]How do I replace a slice of a dataframe column with values from another dataframe column slice?
[英]Assigning column slice with values from another column doesn't throw shape mismatch error
我有一个关于形状广播如何在 Pandas 中工作的问题。 假设我有一个数据框:
df = pd.DataFrame({'A': [1, 2, 3, 4, 5], 'B': [11, 22, 33, 44, 55]})
我尝试用“B”列中的相应值替换“A”列的前两行。
当我尝试将 B 列中的值显式分配为列表时:
df.loc[[0,1], 'A'] = list(df['B'])
我得到明显的形状广播错误:
ValueError: shape mismatch: value array of shape (5,) could not be broadcast to indexing result of shape (2,)
但是当我直接分配B列时:
df.loc[[0,1], 'A'] = df['B']
我没有收到任何错误,Pandas 隐式地对 B 列进行子集化并分配给 A 列。最终输出是
A B
0 11 11
1 22 22
2 3 33
3 4 44
4 5 55
这是预期的行为吗? 为什么 Pandas 在这种情况下不会引发形状不匹配错误?
Pandas 很聪明,因此您可以将广播卸载给它,它只会在指定的索引处分配值。 只要索引匹配,每次将系列分配给列时,这都会起作用。
这是它如何工作的另一个例子:
df = pd.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6],}, index=['a', 'b', 'c'])
df
a b
a 1 4
b 2 5
c 3 6
df.loc[['a', 'b'], 'a'] = pd.Series([4, 5, 6], index=['b', 'c', 'a'])
df
a b
a 6 4
b 4 5
c 3 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.