【问题标题】:Fast access of a subset of rows in a DataFrame快速访问 DataFrame 中的行子集
【发布时间】:2019-03-08 23:32:21
【问题描述】:

我需要访问与多个列值组合关联的 DataFrame 中的行数。

这是我正在做的事情的要点:

for col1, col2, col3 in column_values:
    n = df.loc[(df.col1 == col1) & (df.col2 == col2) & (df.col3 == col3)].shape[0]
    print n

column_values 是一个长列表时,我发现这非常慢。无论我使用df.loc[]df[] 还是df.ix[],速度都是一样的。

有没有更快的方法来访问行数?

【问题讨论】:

  • 不确定你想做什么,但我想说瓶颈不是 df.loc

标签: python pandas performance dataframe optimization


【解决方案1】:

假设 column_values 是一个元组列表,我建议只计算一次:

grouped = df.groupby([col1, col2, col3]).count()
grouped.reindex(columns_values, fill_value=0)

【讨论】:

    猜你喜欢
    • 2016-06-06
    • 1970-01-01
    • 2015-09-06
    • 1970-01-01
    • 2013-07-03
    • 2019-04-15
    • 2018-02-11
    • 1970-01-01
    • 2016-02-24
    相关资源
    最近更新 更多