gpt4 book ai didi

python - Pandas 获取部分数据框并对值进行归一化

转载 作者:太空宇宙 更新时间:2023-11-04 09:25:53 25 4
gpt4 key购买 nike

如下两列的数据框。

我想通过给出日期来选择部分,并标准化(通过使用最小-最大方法)“权重”。

我的计划是这样的:

import pandas as pd


data = {'Date': ["2000-02-01", "2000-03-01", "2000-04-03", "2000-05-01", "2000-06-01", "2000-07-03", "2000-08-01", "2000-09-01", "2000-10-02", "2000-11-01"],
'Weight' : [478, 26, 144, 9, 453, 24, 383, 314, 291, 286]}

df = pd.DataFrame(data)

df_1 = df.loc[df['Date'] >= "2000-04-01"]

df_1 = (df_1 - df_1.min()) / (df_1.max() - df_1.min())

print df_1

# the ideal output is two columns: 1 for Dates after "2000-04-01". 1 for their correspondent normalized "Weights".

它给出了错误:

TypeError: unsupported operand type(s) for -: 'str' and 'str'

我怎样才能实现它?谢谢。

最佳答案

首先将值转换为日期时间,然后仅处理 Weight 列并覆盖 Weight 列:

df['Date']  = pd.to_datetime(df['Date'] )
df_1 = df.loc[df['Date'] >= "2000-04-01"]

a = (df_1['Weight'] - df_1['Weight'].min()) / (df_1['Weight'].max() - df_1['Weight'].min())

print (df_1.assign(Weight = a))
Date Weight
2 2000-04-03 0.304054
3 2000-05-01 0.000000
4 2000-06-01 1.000000
5 2000-07-03 0.033784
6 2000-08-01 0.842342
7 2000-09-01 0.686937
8 2000-10-02 0.635135
9 2000-11-01 0.623874

关于python - Pandas 获取部分数据框并对值进行归一化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57622156/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com