【问题标题】:Pandas: why doesn't dot product work even after choosing the correct number of columns?Pandas:为什么即使选择了正确的列数,点积也不起作用?
【发布时间】:2020-01-26 01:01:36
【问题描述】:

我正在尝试采用 pandas DataFrame 和 Series 的点积。但是,即使我将 pandas DataFrame 限制为与 Series 具有相同的列数,我仍然得到

ValueError:矩阵未对齐。

import pandas as pd
df1 = pd.DataFrame([[0, 1, -2, -1], [1, 1, 1, 1]])
df2 = pd.DataFrame([[0, 1, -2, -1, 1], [1, 1, 1, 1, 1]])
s = pd.Series([1, 1, 2, 1])

print(df1.shape) # (2,4)
print(df2.iloc[:, 1:len(df2.columns)].shape) #(2,4) also

df1.dot(s) # works fine
df2.iloc[:, 1:len(df2.columns)].dot(s) # throws ValueError

为什么会这样?

【问题讨论】:

  • dfdf1df2 是指哪个变量?
  • 对不起,df2。刚刚编辑过。

标签: python pandas


【解决方案1】:

问题是列是 1,2,.. 但索引序列是 0,1,...你需要:

df2.iloc[:, 1:len(df2.columns)].values.dot(s)

df2.values[:,1:].dot(s)

输出

#array([-2,  5])

另一种方法 DataFrame.rename

df2.rename(columns = dict(zip(df2.columns,df2.columns + -1))).iloc[:,1:].dot(s)

n = 1
df2.iloc[:,n:].rename(columns = dict(zip(df2.columns[n:],s.index))).dot(s)
#0   -2
#1    5
#dtype: int64

【讨论】:

    【解决方案2】:

    是索引不匹配! 如果您将 df2s 都转换为数组,则可以:

    > df2.iloc[:, 1:len(df2.columns)].values @ s.values
    array([-2,  5])
    

    如果你的 s 的索引以 1 开头:

    > s.index = [1,2,3,4]
    > df2.iloc[:, 1:len(df2.columns)].dot(s)
    0   -2
    1    5
    dtype: int64
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 2020-02-20
      • 2014-02-25
      相关资源
      最近更新 更多