Pandas什么时候默认播放系列和数据帧?

Jos*_*der 16 python pandas numpy-broadcasting

在试图回答这个问题时,我遇到了一些好奇的东西(对我而言).

假设我想比较一系列形状(10,)和df形状(10,10):

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
Run Code Online (Sandbox Code Playgroud)

正如预期的那样,产生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)
Run Code Online (Sandbox Code Playgroud)

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

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

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

pd.__version__
'0.24.0'
Run Code Online (Sandbox Code Playgroud)

Sco*_*ton 7

发生的事情是使用内在数据对齐的大熊猫.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
Run Code Online (Sandbox Code Playgroud)

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

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
Run Code Online (Sandbox Code Playgroud)

笛卡尔积与重复索引一起发生,匹配为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
Run Code Online (Sandbox Code Playgroud)

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