【问题标题】:How to filter with pandas dataframes vaules greater and less than a mean?如何使用熊猫数据框过滤大于和小于平均值的值?
【发布时间】:2019-10-07 03:03:31
【问题描述】:

。我想在 0.5 0.5 之间的数据框中进行过滤 并将两个过滤后的数据框合并为一个新的数据框。

  1. 有效吗?任何替代品也非常感谢
  2. 请注意,我的原始数据框比代码中给出的示例要大得多。

我希望输出是一个由 mean_depth 过滤的 3 列新数据框。

import pandas as pd
import numpy as np

data= {'x': [462574.63, 462617.91, 462614.76, 462621.02, 462624.16 ], 
       "Y": [5724781.1, 5724750.7, 5724745.7, 5724750.7, 5724755.7 ], 
       "depth": [32.75, 34.74, 35.30, 34.20, 33.73]}
df = pd.DataFrame(data)

df
#df.describe()
mean_depth = 34.144000
# filter to only show the rows in a  0.5 < mean_depth > 0.5 values
# Can this be automated? so that mean_depth not has to be inputed manualy?

【问题讨论】:

  • 感谢您提供良好的示例数据。你能澄清0.5 &lt; mean &gt; 0.5的意思吗?看起来你想要同时小于大于相同值的数字,我想我只是误解了。
  • 你能更清楚你的期望吗
  • 您是指mean_depth - 0.5mean_depth + 0.5 之间的值吗?

标签: python pandas dataframe filtering mean


【解决方案1】:

这是实现“不在平均值的 0.5 以内”过滤器的一种方法。

import pandas
import numpy

data = {
    'x': [462574.63, 462617.91, 462614.76, 462621.02, 462624.16 ], 
    "y": [5724781.1, 5724750.7, 5724745.7, 5724750.7, 5724755.7 ], 
    "depth": [32.75, 34.74, 35.30, 34.20, 33.73]
}

df = pandas.DataFrame(data)

mean = df['depth'].mean()
mean_delta = 0.5
depth = df['depth']
above = depth > mean + mean_delta
below = depth < mean - mean_delta

df[above | below]

【讨论】:

    【解决方案2】:

    IIUC,你需要深度0.5以内的值,你不需要单独计算平均值,

    data= {'x': [462574.63, 462617.91, 462614.76, 462621.02, 462624.16 ], 
           "Y": [5724781.1, 5724750.7, 5724745.7, 5724750.7, 5724755.7 ], 
           "depth": [32.75, 34.74, 35.30, 34.20, 33.73]}
    df = pd.DataFrame(data)
    
    new_df = df[df.depth.between(df.depth.mean() - 0.5, df.depth.mean() + 0.5)]
    
        x           Y           depth
    3   462621.02   5724750.7   34.20
    4   462624.16   5724755.7   33.73
    

    【讨论】:

    • 非常感谢
    猜你喜欢
    • 1970-01-01
    • 2018-05-15
    • 1970-01-01
    • 2021-03-10
    • 1970-01-01
    • 2013-02-14
    • 2020-02-10
    • 1970-01-01
    • 2017-07-25
    相关资源
    最近更新 更多