与
accepted answer
通过
@mozway
链接到您的帖子:
cat = scores.columns.map(category_mapping)
max_transform = scores.T.groupby(cat).transform('max').T
out = scores.where(scores == max_transform, 0)
输出:
CONTESTANT Alligator Beryl Chupacabra Dandelion Eggplant Feldspar
DATE
2024-08-01 0.425859 0.869790 0.000000 0.249784 0.000000 0.000000
2024-08-02 0.545743 0.245658 0.000000 0.000000 0.759137 0.000000
2024-08-03 0.558930 0.773545 0.000000 0.644964 0.000000 0.000000
2024-08-04 0.448075 0.000000 0.000000 0.795700 0.000000 0.807003
2024-08-05 0.858097 0.349170 0.000000 0.445206 0.000000 0.000000
2024-08-06 0.000000 0.847647 0.086368 0.806557 0.000000 0.000000
2024-08-07 0.167334 0.000000 0.000000 0.823477 0.000000 0.709280
# preserve `NaN` values
scores.where((scores == max_transform) | (scores.isna()), 0)
CONTESTANT Alligator Beryl Chupacabra Dandelion Eggplant Feldspar
DATE
2024-08-01 0.425859 0.869790 0.000000 0.249784 0.000000 0.000000
2024-08-02 0.545743 0.245658 0.000000 0.000000 0.759137 NaN
2024-08-03 0.558930 0.773545 0.000000 0.644964 0.000000 NaN
2024-08-04 0.448075 NaN NaN 0.795700 0.000000 0.807003
2024-08-05 0.858097 0.349170 0.000000 0.445206 NaN 0.000000
2024-08-06 NaN 0.847647 0.086368 0.806557 NaN NaN
2024-08-07 0.167334 0.000000 0.000000 0.823477 0.000000 0.709280
数据样本
import pandas as pd
import numpy as np
data = {'index': ['2024-08-01', '2024-08-02', '2024-08-03', '2024-08-04',
'2024-08-05', '2024-08-06', '2024-08-07'],
'columns': ['Alligator', 'Beryl', 'Chupacabra', 'Dandelion',
'Eggplant', 'Feldspar'],
'data': [[0.425859, 0.86979, 0.025546, 0.249784, 0.164426, 0.292931],
[0.545743, 0.245658, 0.384288, 0.148041, 0.759137, np.nan],
[0.55893, 0.773545, 0.215342, 0.644964, 0.204309, np.nan],
[0.448075, np.nan, np.nan, 0.7957, 0.744143, 0.807003],
[0.858097, 0.34917, 0.33974, 0.445206, np.nan, 0.118371],
[np.nan, 0.847647, 0.086368, 0.806557, np.nan, np.nan],
[0.167334, 0.063111, 0.152129, 0.823477, 0.613271, 0.70928]],
'index_names': ['DATE'],
'column_names': ['CONTESTANT']
}
scores = pd.DataFrame.from_dict(data, orient='tight')