【问题标题】:How to get specific number of rows based on column values in dataframe [duplicate]如何根据数据框中的列值获取特定的行数[重复]
【发布时间】:2018-04-02 06:30:02
【问题描述】:

假设我以这种方式拥有一个 MNIST 数据集。

df = pd.read_csv('data/train.csv')
data = df.loc[df['label'].isin([1,6])]

我试图只选择列 ['label'] == 1 或 6 的那些行。

但是,我只想从每列 ['label'] 中获取 500 行

我该怎么做?

【问题讨论】:

  • 也许可以试试df.loc[df['label'].iloc[0:500].isin([1,6])]...
  • 你是指前 500 行吗?然后 df[df.label.isin([1,6]))[0:500] 就可以了。

标签: python pandas dataframe rows


【解决方案1】:

您可以将它们分组并为每个值选择所需的数字:

data = df.loc[df['label'].isin([1,6])].groupby('label').head(500)

【讨论】:

    【解决方案2】:

    先使用 groupby,然后使用 filer,即

    ndf= df.groupby('label').head(500)
    data = ndf.loc[ndf['label'].isin([1,6])]
    

    【讨论】:

      猜你喜欢
      • 2016-11-24
      • 1970-01-01
      • 2021-12-19
      • 2020-01-10
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 2020-12-08
      • 1970-01-01
      相关资源
      最近更新 更多