gpt4 book ai didi

python - 类型错误 : can't multiply sequence by non-int of type 'float' (python 2. 7)

转载 作者:太空狗 更新时间:2023-10-30 02:41:20 24 4
gpt4 key购买 nike

我有一个数据框 t_unit,它是 pd.read_csv() 函数的结果。

datetime    B18_LR_T    B18_B1_T
24/03/2016 09:00 21.274 21.179
24/03/2016 10:00 19.987 19.868
24/03/2016 11:00 21.632 21.417
24/03/2016 12:00 26.285 24.779
24/03/2016 13:00 26.897 24.779

我正在对数据帧重新采样以使用代码计算第 5 个和第 05 个百分位数:

keys_actual = list(t_unit.columns.values)

for key in keys_actual:
ts_wk = t_unit[key].resample('W-MON')
ts_wk_05p = ts_wk.apply(lambda x: x.quantile(0.05)).round(decimals=1).rename(key+'_05p', inplace=True)
ts_wk_95p = ts_wk.apply(lambda x: x.quantile(0.95)).round(decimals=1).rename(key+'_95p', inplace=True)

一切正常,但是当我通过 pd.concat 向我的数据框添加一列时,进入:

datetime    B18_LR_T    B18_B1_T    ext_T
24/03/2016 09:00 21.274 21.179 6.9
24/03/2016 10:00 19.987 19.868 7.5
24/03/2016 11:00 21.632 21.417 9.1
24/03/2016 12:00 26.285 24.779 9.9
24/03/2016 13:00 26.897 24.779 9.2

ts_wk_05p = ts_wk.apply(lambda x: x.quantile(0.05)).round(decimals=1).rename(key+'_05p', inplace=True)

TypeError: can't multiply sequence by non-int of type 'float'

你知道为什么吗?

最佳答案

有一些列不是数字的问题。你可以查看dtypes :

print (t_unit.dtypes)
B18_LR_T float64
B18_B1_T float64
ext_T object
dtype: object

然后尝试先通过 astype 转换为数字:

t_unit.ext_T = t_unit.ext_T.astype(float)

如果:

ValueError: could not convert string to float

然后使用 to_numeric使用参数 errors='coerce' 将错误数据转换为 NaN:

t_unit.ext_T = pd.to_numeric(t_unit.ext_T, errors='coerce')

所有代码:

#simulate string column
t_unit.ext_T = t_unit.ext_T.astype(str)
print (t_unit.dtypes)
B18_LR_T float64
B18_B1_T float64
ext_T object
dtype: object

#convert to float
t_unit.ext_T = t_unit.ext_T.astype(float)

print (t_unit)

L = []
for key in t_unit.columns:
ts_wk = t_unit[key].resample('W-MON')
#remove inplace=True
ts_wk_05p = ts_wk.apply(lambda x: x.quantile(0.05)).round(decimals=1).rename(key+'_05p')
ts_wk_95p = ts_wk.apply(lambda x: x.quantile(0.95)).round(decimals=1).rename(key+'_95p')
L.append(ts_wk_05p)
L.append(ts_wk_95p)


print (pd.concat(L, axis=1))
B18_LR_T_05p B18_LR_T_95p B18_B1_T_05p B18_B1_T_95p ext_T_05p \
datetime
2016-03-28 20.2 26.8 20.1 24.8 7.0

ext_T_95p
datetime
2016-03-28 9.8

关于python - 类型错误 : can't multiply sequence by non-int of type 'float' (python 2. 7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39708133/

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