gpt4 book ai didi

python - 按列对 pandas 数据框进行切片,显示除提供的列之外的所有内容

转载 作者:行者123 更新时间:2023-12-01 04:56:21 26 4
gpt4 key购买 nike

我有一个数据框(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 = sorted_data['account'].isin(account_group)

最佳答案

>>> 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,但他也想通过减去列表来实现:第一个列表是数据帧中的所有行,第二个列表是紫色,第三个是列表一减去列表二,即绿色、蓝色、橙色。因此还有另一个解决方案:

>>> 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

关于python - 按列对 pandas 数据框进行切片,显示除提供的列之外的所有内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27259562/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com