【问题标题】:randomly select n rows from each block - pandas DataFrame [duplicate]从每个块中随机选择 n 行-pandas DataFrame [重复]
【发布时间】:2018-12-21 21:01:59
【问题描述】:

假设我有一个名为 df 的 pandas DataFrame,看起来像这样

father_name   child_name
Robert        Julian
Robert        Emily
Robert        Dan
Carl          Jack
Carl          Rose
John          Lucy
John          Mark
John          Alysha
Paul          Christopher
Paul          Thomas
Robert        Kevin
Carl          Elisabeth

我确信每个父亲都有至少 2个孩子。

我想获得一个 DataFrame,其中每个父亲都有 恰好 2 个孩子,并且这两个孩子是随机选择的。一个示例输出是

father_name   child_name
Robert        Emily
Robert        Kevin
Carl          Jack
Carl          Elisabeth
John          Alysha
John          Mark
Paul          Thomas
Paul          Christopher

我该怎么做?

【问题讨论】:

  • 我猜是有代码的。你从围绕这个问题的研究中尝试了什么?你有错误吗?
  • 我想省力的星期一现在已经延长到了省力的 12 月...请参阅 How to Ask 并提供您的编码尝试的minimal reproducible example

标签: python pandas dataframe subset


【解决方案1】:

您可以对分组数据应用DataFrame.sample。它采用参数 n,您可以将其设置为 2

df.groupby('father_name').child_name.apply(lambda x: x.sample(n=2))\
.reset_index(1, drop = True).reset_index()


father_name child_name
0   Carl    Elisabeth
1   Carl    Jack
2   John    Mark
3   John    Lucy
4   Paul    Thomas
5   Paul    Christopher
6   Robert  Emily
7   Robert  Julian

【讨论】:

    猜你喜欢
    • 2017-01-13
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多