防止Pandas在创建数据帧时强制int到float

2024-09-28 18:57:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我从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

上收缩期指数、下收缩期指数、上收缩期脉冲和下收缩期脉冲均应为整数(如果我检查相关列表中每个元素的类型,则为整数)。但不知何故,当我创建一个数据帧时,四个int中的两个被强制为浮点,尽管我明确指示将它们保持为int

我怀疑这与以下事实有关:列表0-4有一个长度,列表5-10有不同的长度,但大量的谷歌搜索和StackOverflow搜索并没有给出答案

我如何确保我的整数保持整数


Tags: 列表col整数floatupperlowerintheaders
2条回答

如果您执行以下操作:

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

这表明问题在于南部的存在

如果要将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)

菲利波, 非常感谢-dytpe='Int64'加上大写字母'I'就成功了。我不知道这一点,在https://pandas.pydata.org/pandas-docs/stable/user_guide/missing_data.html上写得很好,其中指出pd.Int64Dtype()的别名为“Int64”

再次感谢

托马斯·菲利普斯

相关问题 更多 >