【问题标题】:Drop the values lower than 5 percentile and higher 95 percentile withing each group降低每组中低于 5 个百分点和高于 95 个百分点的值
【发布时间】:2023-02-09 18:33:13
【问题描述】:

我有一些包含以下列的数据集:order_code、city、weight 如何只在数据集中保留有重量的包裹5个百分点<X<95%对于每个城市(类似于 SQL 中的窗口函数(按城市划分))?

df = pd.DataFrame({
    'city': ['LA', 'Berlin', 'Hamburg', 'LA', 'Berlin', 'Hamburg', 'Tokyo', 'Hamburg', 'Berlin', 'Hamburg', 'Hamburg', 'Hamburg', 'Berlin', 'Hamburg', 'Berlin', 'Tokyo', 'Tokyo', 'Tokyo'],
    'weight': [930,933,1577,1018,547,981,1672,598,995,1164,601,1429,1349,1000,618,539,880,1472]
    })

【问题讨论】:

  • 发布可测试的数据框

标签: python pandas numpy


【解决方案1】:

其实我不知道你的数据怎么样。但是我创建了一个数据框。它对所有城市都这样做,然后将其连接起来。但是你当然可以为此创建一个 def 函数。

df = pd.DataFrame({
    'city': ['LA', 'LA', 'Hamburg', 'LA', 'LA', 'Hamburg', 'Hamburg', 'Hamburg'],
    'weight': [500, 1000, 1500, 2000, 1000, 400,100,200]
    })


dfla = df[df['city'] == 'LA']

dfla = dfla[(dfla['weight'] > dfla.weight.quantile(0.05)) | (dfla['weight'] < dfla.weight.quantile(0.95))]
dfhamburg = df[df['city'] == 'Hamburg']
dfhamburg = dfhamburg[(dfhamburg['weight'] > dfhamburg.weight.quantile(0.05)) | (dfhamburg['weight'] < dfhamburg.weight.quantile(0.95))]
df1 = [dfhamburg,dfla]
new_df = pd.concat(df1)
print(new_df)

使用 for 循环:

dflist = []

for f in df['city'].unique():
    df_city = df[df['city'] == str(f)]
    df_city = df_city[(df_city['weight'] > df_city.weight.quantile(0.05)) & (df_city['weight'] < df_city.weight.quantile(0.95))]   
    dflist.append(df_city)

dfe = pd.concat(dflist)

【讨论】:

  • 它变得更难,当有很多城市时 - 超过 500
  • 与我发布的 for 循环一起使用。
猜你喜欢
  • 2020-04-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-08
  • 1970-01-01
  • 1970-01-01
  • 2020-03-19
相关资源
最近更新 更多