gpt4 book ai didi

python - Pandas Dataframe 将列解释为 float 而不是 String

转载 作者:太空狗 更新时间:2023-10-30 01:11:10 35 4
gpt4 key购买 nike

我想将一个 csv 文件导入到 pandas 数据框中。有一个 ID 列,其中仅包含数字,但并非每一行都有一个 ID。

   ID      xyz
0 12345 4.56
1 45.60
2 54231 987.00

我想将此列作为字符串读取,但即使我用

指定它

df=pd.read_csv(filename,dtype={'ID': str})

我明白了

   ID         xyz
0 '12345.0' 4.56
1 NaN 45.60
2 '54231.0' 987.00

是否有一种简单的方法将 ID 作为不带小数点的字符串获取,如 '12345',而无需在导入表后编辑字符串?

最佳答案

一个解决方案可能是这样的,但是在你导入 df 之后:

df = pd.read_csv(filename)
df['ID'] = df['ID'].astype(int).astype(str)

或者因为 NaN 有:

df['ID'] = df['ID'].apply(lambda x: x if pd.isnull(x) else str(int(x)))

关于python - Pandas Dataframe 将列解释为 float 而不是 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53280650/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com