Pandas 非常适合根据索引进行对齐。如果您考虑一下,“意外”结果实际上是可以理解的
x.loc[index1, 3]
作为带有索引标签的系列['a', 'b']
和作业
x.loc[index1, 3] = x.loc[index2, 2]
正在分配新值x.loc[index2, 2]
这是一个带有索引标签的系列['b', 'c']
。因为只有右边的数据aligns系列位于标签左侧'b'
,该标签获得新值,而标签a
被设定为NaN
,因为右侧对于该索引没有值。
当您希望 Pandas 忽略索引时,您需要在右侧传递一个没有索引的对象。所以,正如你所表明的,
y.loc[index1, 3] = y.loc[index2, 2].values
产生所需的结果。
同样,对于更复杂的作业,您可以使用
x.loc[index1, 3] = x.loc[index2, 2].values + 2
or
x.loc[index1, 3] += x.loc[index2, 2].values
(注意第二个赋值使用就地加法运算符,+=
.)
如果您有很多忽略索引的作业,那么也许您应该使用 NumPy 数组而不是 Pandas DataFrame。
import pandas as pd
import numpy as np
x = pd.DataFrame(np.arange(9).reshape((3, 3)), columns=[1, 2, 3], index=['a', 'b', 'c'])
arr = x.values
print(arr)
# [[0 1 2]
# [3 4 5]
# [6 7 8]]
index1 = slice(0,2)
index2 = slice(1,3)
arr[index1, 2] = arr[index2, 1]
print(arr)
# [[0 1 4]
# [3 4 7]
# [6 7 8]]
# Instead of x.loc[index1, 3] = x.loc[index2, 2]+2
arr[index1, 2] = arr[index2, 1] + 2
print(arr)
# [[0 1 6]
# [3 4 9]
# [6 7 8]]
# Instead of x.loc[index1, 3] = x.loc[index1, 3] + x.loc[index2, 2]
arr[index1, 2] += arr[index2, 1]
print(arr)
# [[ 0 1 10]
# [ 3 4 16]
# [ 6 7 8]]
x.loc[:,:] = arr
print(x)
# 1 2 3
# a 0 1 10
# b 3 4 16
# c 6 7 8