簡體   English   中英

如何在Python中將具有對象/類別數據類型的多列熊貓數據框轉換為int64?

[英]how to convert multiple columns of pandas dataframe with object/categorical datatype to int64 in python?

我知道如何在pyton中按一列轉換一列,但是我有很多col與int64或object數據類型混合在一起。

在R中,我可以通過測試is.factor找到這些col索引,然后可以在for循環中將as.numeric應用於轉換。

但是我不知道如何在Python中做。 請幫忙。

如果其他庫中有某種方法,例如numpy,scipy,那也將很棒。

謝謝

就像使用R一樣,您可以使用簡單的for循環來轉換列數據類型。 首先,我們檢查列是否為對象數據類型。 如果是這樣,請嘗試轉換列。 我們使用try語句,因為該列可能無法轉換為整數數據類型。

for c in df.columns:
  if df[c].dtype == 'O':
    try:
        df[c] = df[c].astype('int')
    except:
        print('Column',' ',c,' cannot be converted to int.')

暫無
暫無

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

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