Python 数据整理

标签 python pandas

我有一个 Python 数据框,如下:

print (df)
         Date  Hour  Weight
0  2019-01-01     8       1
1  2019-01-01    16       2
2  2019-01-01    24       6
3  2019-01-02     8      10
4  2019-01-02    16       4
5  2019-01-02    24      12
6  2019-01-03     8      10
7  2019-01-03    16       6
8  2019-01-03    24       5

如何创建一个列 (New_Col),该列将返回当天“体重”最小值的“小时”值。我期待:

Date       Hour  Weight New_Col
2019-01-01  8    1      8
2019-01-01  16   2      8
2019-01-01  24   6      8
2019-01-02  8    10     16 
2019-01-02  16   4      16
2019-01-02  24   12     16
2019-01-03  8    10     24
2019-01-03  16   6      24
2019-01-03  24   5      24

最佳答案

使用GroupBy.transformDataFrameGroupBy.idxmin ,但首先按 Hour 列为每个组的每个最小 WeightHour 值创建索引:

df['New'] = df.set_index('Hour').groupby('Date')['Weight'].transform('idxmin').values
print (df)
         Date  Hour  Weight  New_Col  New
0  2019-01-01     8       1        8    8
1  2019-01-01    16       2        8    8
2  2019-01-01    24       6        8    8
3  2019-01-02     8      10       16   16
4  2019-01-02    16       4       16   16
5  2019-01-02    24      12       16   16
6  2019-01-03     8      10       24   24
7  2019-01-03    16       6       24   24
8  2019-01-03    24       5       24   24

替代解决方案:

df['New'] = df['Date'].map(df.set_index('Hour').groupby('Date')['Weight'].idxmin())

关于Python 数据整理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56210196/

相关文章:

Python 日期时间添加

python - 使用 Matplotlib 创建多个绘图

python - 根据其他字段重新计算pandas数据框字段的更好方法

python - 如何在缺失值 NaN 的条件下将两个数据帧(相同索引)中的值平均到一个 df 中?

python - Login_Required Django 不使用 FormView

python - 在 Python 的 OpenCV 中找不到 cv2.cv 模块

python - 如何使用通配符检查模拟调用?

python - 在 Python/pandas 中使用正则表达式查找城市名称

python - 如何将 pandas value_counts 转换为 python 列表

python - 压缩 Pandas 数据框中的列