我创建了一个多索引数据帧,其中我使用了groupby
平均值。
检查任何特定值的数据类型时
(使用ChkVlu = df.loc['Index1'].loc['index2'].loc['requiredcolumn']
(
我得到的数据类型是numpy.float64
.我需要本机python浮点数的数据类型。
如果我使用ChkVlu = float(ChkVlu)
那么一次只有一个值从 float64 转换为 float,但是在对整个数据帧使用df = df.astype(float)
时,我仍然得到数据类型为 numpy.float64。
我用过df = df.astype(float, copy=False)
和df = df.astype(float, copy=True)
但仍然float64
而不是漂浮。
请帮助我将float64
类型数据帧转换为浮点数。
编辑1 : 在此处发布代码,其中 YearualData.csv 将索引 1 和 index2 作为第 1 2 列,并将年月组合作为下一组列,格式为 2001-01、2001-02、2001-03 .......2016-09、2016-10、2016-11,每行都有数值数据。 我正在转换列名称具有 q1、q2 等的季度数据,每个季度的平均值。
df = pd.read_csv(‘AnnualData.csv')
df.set_index(['index1, 'index2'],inplace = True)
def quarters(col):
if col.endswith(("01", "02", "03")):
final_col = col[:4] + "q1"
elif col.endswith(("04", "05", "06")):
final_col = col[:4] + "q2"
elif col.endswith(("07", "08", "09")):
final_col = col[:4] + "q3"
else:
final_col = col[:4] + "q4"
return final_col
df = df.groupby(quarters, axis = 1).mean()
ChkVlu = df.loc['index1'].loc['index2'].loc['requiredcolumn']
type(ChkVlu)
您可以使用to_numeric,它将为您提供浮点数32
或 np.float32(x(
然后 x.item(( 会给你 python float