【问题标题】:Random Sampling from a column several times in Python/Pandas在 Python/Pandas 中多次从列中随机抽样
【发布时间】:2018-03-16 19:37:36
【问题描述】:

我是 Pandas 和 Python 的新手。我将通过一个例子来写我的问题。我有一个数据,例如

df = pd.DataFrame([[1, 2], [1, 3], [4, 6], [5,6], [7,8], [9,10], [11,12], [13,14]], columns=['A', 'B'])
df 
    A   B

0   1   2

1   1   3

2   4   6

3   5   6

4   7   8

5   9   10

6   11  12

7   13  14

我从两列中抽取 3 个样本。

x = df['A'].sample(n=3)
x = x.reset_index(drop=True)
x

0     7
1     9
2    11

y = df['B'].sample(n=3)
y = y.reset_index(drop=True)
y

0     6
1    12
2     2

我想进行 10 次采样 (n=3)。 我试过[y] * 10,它在 6、12、2 中产生 10 次列。我想从主要数据中执行 10 次。然后我想从 A 和 B 生成的这些新列中创建一个新数据。 我想也许我应该写 for 循环,但我对它们不太熟悉。

感谢您的帮助。

【问题讨论】:

  • 那么,让我来做对了……你想要相同的 3 个值重复 10 次吗?
  • 你想要的输出是什么?您是否想要更换样品?
  • 哦,不,我不想要相同的 3 个值。每次我都希望从 df 数据框中获取新数据。 10 次新数据,来自 A 和 B 列。

标签: python pandas dataframe random


【解决方案1】:

正如 WeNYoBen 所展示的,将任务拆分为一个很好的做法

  1. 生成样本重复,
  2. 连接数据帧。

我的建议:编写一个 generator 函数,用于创建样本重复的生成器(而不是列表)。然后,您可以连接生成器生成的项目(在本例中为数据帧)。

# a generator function
def sample_rep(dframe, n=None, replicates=None):
    for i in range(replicates):
        yield dframe.sample(n)

d = pd.concat(sample_rep(df, n=3, replicates=10),
              keys=range(1, 11), names=["replicate"])

生成器占用的内存更少,因为它可以即时生成所有内容。 pd.concat() 函数会在您的数据帧上触发 sample_rep(),从而生成要连接的数据帧列表。

【讨论】:

    【解决方案2】:

    看来你需要

    df.apply(lambda x : x.sample(3)).apply(lambda x : sorted(x,key=pd.isnull)).dropna().reset_index(drop=True)
    Out[353]: 
          A     B
    0   7.0   2.0
    1  11.0   6.0
    2  13.0  12.0
    

    抱歉误导,我忽略了10次

    l=[]
    count = 1
    while (count < 11):
       l.append(df.apply(lambda x : x.sample(3)).apply(lambda x : sorted(x,key=pd.isnull)).dropna().reset_index(drop=True))
       count = count + 1
    
    pd.concat(l)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-07
      • 2018-09-12
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 2013-04-13
      • 1970-01-01
      相关资源
      最近更新 更多