我从11个列表中创建了一个数据框。这些列表中有四个是整型列表,其余七个是浮点型列表。我使用以下命令从所有11个列表创建数据帧
df = pd.DataFrame({ col_headers[0] : pd.Series(upper_time, dtype='float'),
col_headers[1] : pd.Series(upper_pres, dtype='float'),
col_headers[2] : pd.Series(upper_indx, dtype='int'),
col_headers[3] : pd.Series(upper_pulses, dtype='int'),
col_headers[4] : pd.Series(median_upper_pulses, dtype='float'),
col_headers[5] : pd.Series(lower_time, dtype='float'),
col_headers[6] : pd.Series(lower_pres, dtype='float'),
col_headers[7] : pd.Series(lower_indx, dtype='int'),
col_headers[8] : pd.Series(lower_pulses, dtype='int'),
col_headers[9] : pd.Series(median_lower_pulses, dtype='float'),
col_headers[10] : pd.Series(median_both_pulses, dtype='float')
})不幸的是,当我输入df.dtypes时。我得到了
df.dtypes
Upper Systole Time float64
Upper Systole Pressure float64
Upper Systole Index int32
Upper Systole Pulses int32
Median Upper Systolic Pulses float64
Lower Systole Time float64
Lower Systole Pressure float64
Lower Systole Index float64
Lower Systole Pulses float64
Median Lower Systolic Pulses float64
Median Both Systolic Pulses float64
dtype: object上层系统窃取索引,下层系统窃取索引,上层系统窃取脉冲和下层系统窃取脉冲都应该是整数(如果我检查相关列表中每个元素的类型,它们就是整数)。但不知何故,当我创建一个数据帧时,四个整型中的两个被强制转换为浮点型,尽管我明确指示将它们保留为整型。
我怀疑这与列表0-4有一个长度,而列表5-10有不同的长度有关,但是很多谷歌和搜索StackOverflow都没有得到答案。
我如何确保我的整型保持整型?
发布于 2020-06-06 16:59:45
如果您执行以下操作:
pd.DataFrame({"A":pd.Series([1,2,3,4], dtype='int'),
"B": pd.Series([1,3], dtype='int')}).astype(int)您将得到以下错误:
867 if not np.isfinite(arr).all():
--> 868 raise ValueError("Cannot convert non-finite values (NA or inf) to integer")
869
870 elif is_object_dtype(arr):
ValueError: Cannot convert non-finite values (NA or inf) to integer这表明问题出在NaNs的存在。
如果要将NaN值转换为整数,例如0,则应该能够使用.astype(int)将指定的列强制转换为整数
示例:
df = pd.DataFrame({"A":pd.Series([1,2,3,4], dtype='int'),
"B": pd.Series([1,3], dtype='int')})
df["B"] = df["B"].fillna(0).astype(int)发布于 2020-06-06 17:18:57
filippo,非常感谢- dytpe = 'Int64‘,大写的'I’做到了。我没有意识到这一点,它在https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html中写得很好,在那里它声明pd.Int64Dtype()是'Int64‘的别名。
再次感谢
托马斯·菲利普斯
https://stackoverflow.com/questions/62229352
复制相似问题