一个两列的数据框,如下所示。
我想给日期指定一个部分,然后将“权重”归一化(使用最小-最大方法)。
这是我的计划:
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'
如何实现?谢谢。
答案 0 :(得分:2)
首先将值转换为日期时间,然后仅处理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
答案 1 :(得分:2)
日期列的数据类型为字符串。因此您必须将其更改为。为此,您可以使用此方法==>
df['Date']=pd.to_datetime(df['Date'])