【问题标题】:Taking a proportion of a dataframe based on column values根据列值获取数据框的一部分
【发布时间】:2019-01-10 12:38:01
【问题描述】:

我有一个大约 50,000 行的 Pandas 数据框,我想根据一些条件从该数据框中随机选择一定比例的行。具体来说,我有一个名为“使用类型”的列,对于该列中的每个字段,我想选择不同比例的行。

例如:

df[df['type of use'] == 'housing'].sample(frac=0.2)

此代码返回 20% 的所有行的“使用类型”为“住房”。问题是我不知道如何以“惯用”的方式对其余字段执行此操作。我也不知道如何从这个采样中获取结果来形成一个新的数据框。

【问题讨论】:

  • 您需要遍历所有独特的过滤器选项并存储在数据框字典中,请查看下面的答案。

标签: python pandas numpy


【解决方案1】:

您可以通过list(df['type of use'].unique()) 为列中的所有值创建一个唯一列表,并如下迭代:

for i in list(df['type of use'].unique()):
    print(df[df['type of use'] == i].sample(frac=0.2))

i = 0 
while i < len(list(df['type of use'].unique())):
    df1 = df[(df['type of use']==list(df['type of use'].unique())[i])].sample(frac=0.2)
    print(df1.head())
    i = i + 1

为了存储,你可以创建一个字典:

dfs = ['df' + str(x) for x in list(df2['type of use'].unique())]
dicdf = dict()
i = 0 
while i < len(dfs):
    dicdf[dfs[i]] = df[(df['type of use']==list(df2['type of use'].unique())[i])].sample(frac=0.2)
    i = i + 1
print(dicdf)

这将打印数据帧的字典。 您可以打印您想看到的内容,例如房屋样本:print (dicdf['dfhousing'])

【讨论】:

  • 非常感谢,@anky_91。这通常是我试图实现的目标。我正在考虑在 SQL 中为其他东西“复制”我的代码 - 例如,您是否知道是否存在与 df[df['type of use'] == i].sample(frac=0.2) 等效的 SQL?
【解决方案2】:

抱歉,这晚了 2 年多,但我认为您可以在不重复的情况下做到这一点,基于我收到的类似问题 here 的帮助。将其应用于您的数据:

import pandas as pd
import math
percentage_to_flag = 0.2 #I'm assuming you want the same %age for all 'types of use'?

#First, create a new 'helper' dataframe:
random_state = 41  # Change to get different random values.
df_sample = df.groupby("type of use").apply(lambda x: x.sample(n=(math.ceil(percentage_to_flag * len(x))),random_state=random_state))
df_sample = df_sample.reset_index(level=0, drop=True)  #may need this to simplify multi-index dataframe

# Now, mark the random sample in a new column in the original dataframe:
df["marked"] = False
df.loc[df_sample.index, "marked"] = True

【讨论】:

    猜你喜欢
    • 2018-10-18
    • 2021-11-08
    • 1970-01-01
    • 2021-06-11
    • 2021-09-11
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多