如何在熊猫数据帧 (Python) 中将单元格的新值设置为浮点数 - 在嵌套 for 循环中,数据帧将舍入为整数



找到解决方案:我需要更改数据帧的数据类型:

for p in periods:
df['Probability{}'.format(p)] = 0
for p in periods:
df['Probability{}'.format(p)] = float(0)

或者按照下面批准的答案进行操作。


我断言单元格的新值为浮点数,但它们被设置为整数,我不明白为什么。 它是包含嵌套循环的数据挖掘项目的一部分。

我正在使用Python 3。

我尝试了不同的模式,用熊猫写进一个单元格:df.at[index,col] = float(val)df.set_value[index,col,float(val)],以及df[col][index] = float(val)但他们都没有提供解决方案。我得到的输出是:

In: print(df[index][col])
Out: 0
In: print(val)
Out: 0.4774410939826658

这是循环的简化版本

periods = [7,30,90,180]
for p in periods:
df['Probability{}'.format(p)] = 0        
for i in range(len(df.index)):
for p in periods:
if i >= p - 1:
# Getting relevant data and computing value 
vals = [df['Close'][j] for j in range(i - p, i)]
probability = (len([j for j in vals if j>0])/len(vals))
# Asserting value to cell in pd.dataframe          
df.at[df.index[i], 'Probability{}'.format(p)] = float(probability)

我不明白为什么是熊猫。数据帧正在将浮点数更改为整数,并向上舍入或向下舍入。当我直接在控制台中向单元格断言值时,我没有遇到任何问题。

这个问题有什么解决方法或解决方案吗?

在嵌套 for 循环之前,我没有问题,以避免硬编码大量琐碎的代码。

注意:似乎如果我分解,例如用100 * val = new_val,它只会分解四舍五入的数字。因此,如果我乘以100*val = new_val = 0,因为数字向下舍入为0.

我还尝试更改数据帧的数据类型:

df = df.apply(pd.to_numeric)

万事如意。

数据帧中的数据类型不正确似乎存在问题。您上次尝试转换整个df可能非常接近。尝试使用

df['Close'] = pd.to_numeric(df['Close'], downcast="float")

最新更新