【问题标题】:slice pandas dataframe by column showing all except the column provided按列切片 pandas 数据帧,显示除提供的列之外的所有数据
【发布时间】:2014-12-02 21:44:22
【问题描述】:

我有一个看起来像这样的数据框 (df)

category | amount | freq
green         10     1
blue          5      2
orange        7      3
purple        5      4

我只想选择“频率”和“金额”列,以及除紫色行之外的所有行

我知道我可以使用 df.ix 来选择这样的列

df.ix[['green','blue','orange'],['freq','amount']]

但是,如何获取类别列中的唯一值,并选择不是紫色的列?

df.set_index(['category'])

更新

请参阅 Roman Pekar 的过滤掉不需要的行的解决方案。

对于多行,创建一个系列或一个列表(即 account_group)并像这样引用它。

names = sorted_data[sorted_data.account.isin(account_group)]

这样做 names 是一个数据框。

然而,这是相似但不正确的语法,这将返回一个系列。

names = sorted_data['account'].isin(account_group)

【问题讨论】:

    标签: python pandas slice


    【解决方案1】:
    >>> df
      category  amount  freq
    0    green      10     1
    1     blue       5     2
    2   orange       7     3
    3   purple       5     4
    
    >>> df[df['category'] != 'purple'][['amount','freq']]
       amount  freq
    0      10     1
    1       5     2
    2       7     3
    

    更新不确定我是否正确理解了 OP,但他也想这样做 by subtracting lists: the first list is all the rows in the dataframe, the second is purple, and the third would be list-one minus list-two which would be green, blue, orange。因此另一种解决方案:

    >>> l1
    ['green', 'blue', 'orange', 'purple']
    >>> l2
    ['purple']
    >>> l3 = [x for x in l1 if x not in l2]
    >>> l3
    ['green', 'blue', 'orange']
    >>> df[df['category'].isin(l3)][['amount','freq']]
       amount  freq
    0      10     1
    1       5     2
    2       7     3
    

    【讨论】:

    • 感谢 Roman Pekar,是否也可以通过减去列表来完成:第一个列表是数据框中的所有行,第二个是紫色,第三个是 list-one 减去 list-2会是绿色、蓝色、橙色吗?这可能吗?
    • 是否可以在切片的同一操作中过滤列,例如:“df[df['category'] !='purple'][['amount','freq '==[3,5]]]"
    • 你可以这样做df[(df['category'] == 'blue') & (df['amount'] == 5) & (df['freq'] == 2)]
    • 是否可以按照您的答案做同样的事情,但要做到!="category1","category2","category3"
    • ~df['category'].isin("category1","category2","category3")
    猜你喜欢
    • 1970-01-01
    • 2019-07-22
    • 2017-05-24
    • 2018-01-30
    • 2021-10-17
    • 2017-08-11
    • 2015-05-09
    • 2019-04-01
    • 2015-05-21
    相关资源
    最近更新 更多