python-3.x - 如何根据另一列中的某些值创建新列

标签 python-3.x pandas dataframe

每天,我都会使用不同的颜色。我需要创建一个新列,用于查看每种颜色的用户与第一天的比率。

例如,对于蓝色,最早的日期是 2020-01-01,对应的“users”值为 100。因此,对于 2020-01-02 >,我想要的值应该是102/100 = 1.02

raw_data = [
        {'date': '2020-01-01', 'color': 'blue', 'users': 100},
        {'date': '2020-01-02', 'color': 'blue', 'users': 102},
        {'date': '2020-01-03', 'color': 'blue', 'users': 104},
        {'date': '2020-01-04', 'color': 'blue', 'users': 98},
        {'date': '2020-01-02', 'color': 'red', 'users': 100},
        {'date': '2020-01-03', 'color': 'red', 'users': 107},
        {'date': '2020-01-04', 'color': 'red', 'users': 114},
        {'date': '2020-01-05', 'color': 'red', 'users': 150},
    ]

到目前为止,我知道我可以使用下面的代码获取每种颜色的最短日期,但不确定下一步该怎么做

grouped = df.groupby('color')['date']
min = grouped.min()

最佳答案

Date 数据帧的值进行排序,然后对 color 进行 groupby 并转换列 users 使用 first,然后使用 Series.divusers 除以此转换后的列以获得比率:

df['date'] = pd.to_datetime(df['date'])
df['ratio'] = df['users'].div(
    df.sort_values('date').groupby('color')['users'].transform('first')
)

        date color  users  ratio
0 2020-01-01  blue    100   1.00
1 2020-01-02  blue    102   1.02
2 2020-01-03  blue    104   1.04
3 2020-01-04  blue     98   0.98
4 2020-01-02   red    100   1.00
5 2020-01-03   red    107   1.07
6 2020-01-04   red    114   1.14
7 2020-01-05   red    150   1.50

关于python-3.x - 如何根据另一列中的某些值创建新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63965770/

相关文章:

python - 删除列表中的所有电子邮件,不包括 gmails

r - 根据行名匹配两个数据框并添加 NA

python - 数据帧迭代以比较行而无需 for 循环

python - 在任何列中搜索关键字的数据框并获取行

Python如何将列表打印到列表

python-3.x - 如何在 FastAPI 中使用带路由的中间件

python-3.x - 如何修复使用 sklearn.mixture.GaussianMixture 拟合 GMM 时的 ValueError?

pandas - 计算每个股价随时间的滚动指数加权移动平均值

python - 如何循环遍历 Pandas DataFrame 并将字符串拆分为多行

python - 两个数组的高效匹配(KDTree的使用方法)