python - 访问 pandas 数据框中单行的推荐方法?

标签 python python-3.x pandas

我经常想使用多个条件选择 Pandas DataFrame 的单行。

为了进一步处理,将其作为系列或字典访问是有用的,而不是作为 1xW DataFrame 访问。

我可以这样做:

r = df.loc[ (df['col1'] == v1) & (df['col2'] == v2) ]
if len(r.index) != 1:
  raise ValueError(...)
r = r.iloc[0]

这感觉有点笨拙。有更好的推荐方法吗?

最佳答案

所有内置访问器都不会执行您想要的操作。您可以构建自己的访问器并对其进行猴子修补:

def get(df, **kwargs):
    cond = [True] * df.shape[0]
    for col, value in kwargs.items():
        cond &= df[col] == value

    result = df[cond]
    if result.shape[0] > 1:
        raise ValueError('Key must be unique')
    return result.iloc[0]

pd.DataFrame.get = get

# Usage
df.get(col1=..., col2=..., col3=...)

但是,这相对较慢,因此不要在紧密循环中调用它。

关于python - 访问 pandas 数据框中单行的推荐方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58380548/

相关文章:

Python rawkit 如何从 RAW 文件中读取元数据值?

python - 使用 Numpy polyadd() 添加两个多项式

python - CreateView 创建两个模型对象

python - 从 pandas 数据帧列创建指定长度的组

numpy - 与ndarray相关的DataFrame.mul使用错误

python - 在 ManyToManyField 中定义最大关系

Python多处理池: how to join the reasults in a parallel way?

excel - Python Xlsx Writer - 将字符串写入新行

python - Notify.Notification 中的 PyGObject 进度条

python - 将 Python Pandas 数据框相乘以获得列中值的乘积