pd.to_numeric 后对象未转换为数字
object is not converting to numeric after pd.to_numeric
我不明白为什么我的专栏 allHoldingsFund['ratioBest'] 没有转换成数字?
最初我用数字 0 替换了空行,但是 int 0 和浮点数并没有使列 allHoldingsFund['ratioBest'] 容易转换为数字(出现错误 TypeError: len() of unsized object)。现在我保留了空行,并强制将浮点数转换为数字,但它不起作用 - allHoldingsFund['ratioBest'] 仍然是一个对象。见下文
allHoldingsFund['ratioBest']
Out[170]:
100
144
187 0.520704845814978
264
386
494
597
635 2.790492957746479
allHoldingsFund['ratioBest']=pd.to_numeric(allHoldingsFund['ratioBest'], errors='coerce')
Name: ratioBest, Length: 1664, dtype: object
感谢任何帮助
谢谢
我明白你的问题 - 值不是标量,而是 numpy.ndarray
s:
allHoldingsFund = pd.DataFrame({'ratioBest':[np.array(4.12), '']})
print (allHoldingsFund)
ratioBest
0 4.12
1
解决方案是转换为 list
,然后转换为 1d array
:
arr = np.array(allHoldingsFund['ratioBest'].tolist())
allHoldingsFund['ratioBest'] = (pd.to_numeric(arr, errors='coerce'))
print (allHoldingsFund)
ratioBest
0 4.12
1 NaN
print (allHoldingsFund['ratioBest'].dtype)
float64
我不明白为什么我的专栏 allHoldingsFund['ratioBest'] 没有转换成数字?
最初我用数字 0 替换了空行,但是 int 0 和浮点数并没有使列 allHoldingsFund['ratioBest'] 容易转换为数字(出现错误 TypeError: len() of unsized object)。现在我保留了空行,并强制将浮点数转换为数字,但它不起作用 - allHoldingsFund['ratioBest'] 仍然是一个对象。见下文
allHoldingsFund['ratioBest']
Out[170]:
100
144
187 0.520704845814978
264
386
494
597
635 2.790492957746479
allHoldingsFund['ratioBest']=pd.to_numeric(allHoldingsFund['ratioBest'], errors='coerce')
Name: ratioBest, Length: 1664, dtype: object
感谢任何帮助
谢谢
我明白你的问题 - 值不是标量,而是 numpy.ndarray
s:
allHoldingsFund = pd.DataFrame({'ratioBest':[np.array(4.12), '']})
print (allHoldingsFund)
ratioBest
0 4.12
1
解决方案是转换为 list
,然后转换为 1d array
:
arr = np.array(allHoldingsFund['ratioBest'].tolist())
allHoldingsFund['ratioBest'] = (pd.to_numeric(arr, errors='coerce'))
print (allHoldingsFund)
ratioBest
0 4.12
1 NaN
print (allHoldingsFund['ratioBest'].dtype)
float64