【问题标题】:numpy.logical_and.reduce on pandas.DataFramepandas.DataFrame 上的 numpy.logical_and.reduce
【发布时间】:2019-01-25 20:05:13
【问题描述】:

版本是 python==3.6.6pandas==0.23.0numpy==1.15.0。我想获取 DataFrames 列表的交集。

例如,

x = pd.DataFrame(
    np.arange(6).reshape((3, 2)),
    index=["a", "b", "c"],
    columns=["q", "e"]
)

y = x - 1

预期的回报是 np.logical_and(x, y) 返回的

       q      w
a  False  False
b   True   True
c   True   True

但是,np.logical_and.reduce([x, y]) 会引发错误:

ValueError: 无法将大小为 3 的序列复制到维度为 2 的数组轴

然后,我尝试了

x = pd.DataFrame(
    np.arange(4).reshape((2, 2)),
    index=["a", "b"],
    columns=["q", "e"]
)

y = x - 1
np.logical_and.reduce([x, y])

出现另一个错误:

ValueError: int() 以 10 为底的无效文字:'q'

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    而不是做:

    np.logical_and.reduce([x, y])
    

    做:

    np.logical_and.reduce([x.values, y.values])
    

    输出

    [[False False]
     [ True  True]
     [ True  True]]
    

    第一个将操作应用于 DataFrame(不是 numpy 数组),第二个将操作应用于 DataFrame x.values 的值,表示为 numpy 数组;

    【讨论】:

      【解决方案2】:
      import pandas as pd
      import numpy as np
      df = pd.DataFrame({'col1': [1, 2, 3, 4, 5], 
                    'col2': [7, 45, 12, 56, 14],
                    'col3': [56, 67, 8, 12, 39],
                    'col4': [16, np.nan, 25, 6, 19],
                    'col5': [1, 9, 23, 56, np.nan],
                    'col6': [13, 3, 53, 72, 88]})
      print(df)
      df2 = (df%2).replace(1, np.nan)==0
      print('\n',df2)
      print('\nOdd numbers mean {}'.format([df[col][np.logical_and.reduce([df2[col].values == False])].mean() for col in df.columns]))
      print('\nEven numbers mean {}'.format([df[col][np.logical_and.reduce([df2[col].values == True])].mean() for col in df.columns]))
      

      【讨论】:

        猜你喜欢
        • 2017-08-27
        • 2021-03-06
        • 2014-08-19
        • 1970-01-01
        • 1970-01-01
        • 2014-10-01
        • 2016-11-20
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多