gpt4 book ai didi

python - 排除 Pandas 数据框中索引行的最有效方法

转载 作者:太空狗 更新时间:2023-10-30 02:04:25 25 4
gpt4 key购买 nike

我对 Python 和 Pandas 比较陌生,并且正在努力处理(分层)索引。我已经掌握了基础知识,但对更高级的切片和横截面却一头雾水。

例如,使用以下数据框

import pandas as pd
import numpy as np
data = pd.DataFrame(np.arange(9).reshape((3, 3)),
index=pd.Index(['Ohio', 'Colorado', 'New York'], name='state'), columns=pd.Index(['one', 'two', 'three'], name='number'))

我想选择除索引为“Colorado”的行以外的所有内容。对于小型数据集,我可以这样做:

data.ix[['Ohio','New York']]

但是如果唯一索引值的数量很大,那是不切实际的。天真地,我希望语法像

data.ix[['state' != 'Colorado']]

但是,这只会返回第一条记录“Ohio”,而不会返回“New York”。这可行,但很麻烦

filter = list(set(data.index.get_level_values(0).unique()) - set(['Colorado']))
data[filter]

肯定有更 Pythonic 的、冗长的方法来做到这一点?

最佳答案

这是一个 Python 问题,而不是 pandas 问题:'state' != 'Colorado' 是 True,所以 pandas 得到了什么是 data.ix[[True]]

你可以做

>>> data.loc[data.index != "Colorado"]
number one two three
state
Ohio 0 1 2
New York 6 7 8

[2 rows x 3 columns]

或使用 DataFrame.query :

>>> data.query("state != 'New York'")
number one two three
state
Ohio 0 1 2
Colorado 3 4 5

[2 rows x 3 columns]

如果你不喜欢数据的重复。 (引用传递给 .query() 方法的表达式是解决这个事实的唯一方法之一,否则 Python 会在 pandas 看到它之前评估比较。)

关于python - 排除 Pandas 数据框中索引行的最有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21650809/

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