python - 使用 np.where 根据条件返回 df 行的平均值

标签 python pandas numpy where-clause np

假设我有以下代码

import pandas as pd
import numpy as np

flag = pd.DataFrame({'flag': [ [], ['red'], ['red, green'], ['red, blue'], ['blue'] ]})
colors_values = pd.DataFrame({'red': [1, 1, 1, 1, 1], 'green': [2, 2, 2, 2, 2], 'blue': [4, 4, 4, 4, 4]})

enter image description here enter image description here

我有一个名为“flag”的一维 df,每行包含一个颜色列表(红色、绿色、蓝色)和另一个具有这些颜色名称的 df“colors_values”。它们的行数相同。

我的目标是使用 np.where 返回基于“flag”的“colors_values”每一行的值的平均值。输出将是这样的:

enter image description here

如果有更好/更快的方法来代替使用 np.where,我想知道。

最佳答案

Pandas 合并非常快,如果您允许一些加速时间,您可以进行合并/分组:

df_flag = flag.explode('flag').reset_index()
df_colors = colors_values.reset_index().melt(ignore_index=False, var_name='flag').reset_index()
df_flag = df_flag.merge(df_colors, on=['index', 'flag'], how='left')

df_grouped = df_flag.groupby(['index'])['value'].mean()

关于python - 使用 np.where 根据条件返回 df 行的平均值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75420647/

相关文章:

python - 从 XML DTD 生成 lex 匹配规则和 yacc 语法规则

python - 检测图像是否像素化的最佳方法是什么?

python-2.7 - python Pandas : set a value of column based on another value of a column in a list

python - pickle ,numpy - reshape 参数?

python - 如何从结构化 numpy 数组中删除列?

python - 在 Python 中获取变量名?

python - 如果列表项在另一个列表中同时保持顺序,如何将它们移到前面

python - 在 pandas Dataframe 中移动数据

python - Pandas Dataframe 中的列和行的迭代

python - 为什么 `numpy.fft.irfft` 如此不精确?