簡體   English   中英

將Pandas DataFrame中的列類型更改為int64

[英]Changing Column Type in Pandas DataFrame to int64

我正在嘗試使用.map()在DataFrame中將列的數據類型從type: object更改為type: int64

   df['one'] = df['one'].map(convert_to_int_with_error)

這是我的功能:

def convert_to_int_with_error(x):
    if not x in ['', None, ' ']:
        try:
            return np.int64(x)
        except ValueError as e:
            print(e)
            return None
    else:
        return None

    if not type(x) == np.int64():
        print("Not int64")
        sys.exit()

這成功完成。 但是,當我在完成后檢查數據類型時,它恢復為type: float

print("%s is a %s after converting" % (key, df['one'].dtype))

我認為問題在於您將有問題的值從None轉換為NaN ,因此將int NaN轉換為float -see docs

相反, map你可以使用to_numeric與參數errors='coerce'有問題的值轉換為NaN

df['one'] = pd.to_numeric(df['one'], errors='coerce')

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM