【问题标题】:Pandas subset of DataFrame with fixed number of value per class [duplicate]DataFrame 的 Pandas 子集,每个类具有固定数量的值 [重复]
【发布时间】:2019-10-08 16:19:31
【问题描述】:

我有一个 pandas DataFrame df,其中包含一个列 ID 和一个列 Type。这是一个例子:

print(df)

>>
+---------+---------+
|       ID|     Type|
+---------+---------+
|      AAA|        A|
|      BBB|        B|
|      CCC|        B|
|      DDD|        A|
|      EEE|        B|
|      FFF|        A|
|      GGG|        B|
+---------+---------+

从该 DataFrame 中,我想为每个 Type 提取一个带有 X 不同值的子 DataFrame。

这里是前面的例子(顺序无关紧要):

X = 2
new_df = do_something(df, X)
print(new_df)

>>
+---------+---------+
|       ID|     Type|
+---------+---------+
|      AAA|        A|
|      DDD|        A|
|      BBB|        B|
|      CCC|        B|
+---------+---------+

有简单的方法吗?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    使用pandas.DataFrame.groupby.head:

    import pandas as pd
    
    df.groupby('Type').head(2)
    

    输出:

        ID Type
    0  AAA    A
    1  BBB    B
    2  CCC    B
    3  DDD    A
    

    【讨论】:

      猜你喜欢
      • 2017-03-30
      • 2016-06-01
      • 2021-06-15
      • 2016-02-19
      • 2020-07-28
      • 1970-01-01
      • 2022-11-24
      • 2023-02-10
      • 2017-12-23
      相关资源
      最近更新 更多