python - Pandas 什么时候默认广播 Series 和 Dataframes?

标签 python pandas array-broadcasting

我在尝试回答 this question 时遇到了一些(对我来说)好奇的事情.

假设我想将一系列形状 (10,) 与形状 (10,10) 的 df 进行比较:

np.random.seed(0)
my_ser = pd.Series(np.random.randint(0, 100, size=10))
my_df = pd.DataFrame(np.random.randint(0, 100, size=100).reshape(10,10))
my_ser > 10 * my_df

如预期的那样,生成 df (10,10) 形状的矩阵。比较似乎是按行进行的。

但是考虑这种情况:

df = pd.DataFrame({'cell1':[0.006209, 0.344955, 0.004521, 0, 0.018931, 0.439725, 0.013195, 0.009045, 0, 0.02614, 0],
              'cell2':[0.048043, 0.001077, 0,0.010393, 0.031546, 0.287264, 0.016732, 0.030291, 0.016236, 0.310639,0], 
              'cell3':[0,0,0.020238, 0, 0.03811, 0.579348, 0.005906, 0,0,0.068352, 0.030165],
              'cell4':[0.016139, 0.009359, 0,0,0.025449, 0.47779, 0, 0.01282, 0.005107, 0.004846, 0],
              'cell5': [0,0,0,0.012075, 0.031668, 0.520258, 0,0,0,2.728218, 0.013418]})
i = 0
df.iloc[:,i].shape
>(11,)
(10 * df.drop(df.columns[i], axis=1)).shape
>(11,4)
(df.iloc[:,i] > (10 * df.drop(df.columns[i], axis=1))).shape
>(11,15)

据我所知,这里 Pandas 使用 df 广播系列。这是为什么?

可以通过以下方式获得所需的行为:

(10 * df.drop(df.columns[i], axis=1)).lt(df.iloc[:,i], axis=0).shape
>(11,4)

pd.__version__
'0.24.0'

最佳答案

正在发生的是使用固有数据对齐的 pandas。 Pandas 几乎总是对齐索引上的数据,行索引或列标题。这是一个简单的例子:

s1 = pd.Series([1,2,3], index=['a','b','c'])
s2 = pd.Series([2,4,6], index=['a','b','c'])
s1 + s2
#Ouput as expected:
a    3
b    6
c    9
dtype: int64

现在,让我们运行其他几个具有不同索引的示例:

s2 = pd.Series([2,4,6], index=['a','a','c'])
s1 + s2
#Ouput
a    3.0
a    5.0
b    NaN
c    9.0
dtype: float64

笛卡尔乘积出现重复索引,匹配为 NaN + value = NaN。

并且,没有匹配的索引:

s2 = pd.Series([2,4,6], index=['e','f','g'])
s1 + s2
#Output
a   NaN
b   NaN
c   NaN
e   NaN
f   NaN
g   NaN
dtype: float64

因此,在您的第一个示例中,您创建的 pd.Series 和 pd.DataFrame 具有匹配的默认范围索引,因此比较按预期进行。在您的第二个示例中,您将列标题 ['cell2','cell3','cell4','cell5'] 与默认范围索引进行比较,该索引返回所有 15 列并且没有匹配项,所有值都将为 False,NaN 比较返回 False。

关于python - Pandas 什么时候默认广播 Series 和 Dataframes?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54731343/

相关文章:

python - 读取 json 图 networkx 文件

python - numpy - 向量化函数 : apply_over_axes/apply_along_axis

Python:获取数组所有掩码的最快方法

python - 在 Numpy 中将一维数组添加到三维数组

python - 带有列表的 Pandas 数据框中的唯一项目

python - 带额外字段的 flask sqlalchemy多对多

python - Python多线程通信效率

Python 将字典转换为数据框失败

python - 如何在没有任何索引的情况下合并两个数据帧

python - Pandas 分组