簡體   English   中英

遍歷列並重新分配值-Pandas / Python

[英]Iterating over columns and reassigning values - Pandas/Python

嘗試使用for循環遍歷列並將“是”和“否”更改為1和0。

出於某種原因,嘗試執行此操作時收到無效的類型比較錯誤:

Panda DataFrame具有多個列,其中之一為“組合”

for col,row in d.iteritems():
    d.loc[d[col] == 'No', col] = 0
    d.loc[d[col] == 'Yes', col] = 1

TypeError:無效的類型比較

為了進行比較,我可以在沒有問題的單個列上成功執行此操作:

d.loc[d['Combined'] == 'No', 'Combined'] = 0
d.loc[d['Combined'] == 'Yes', 'Combined'] = 1

為何將col的值插入loc函數以代替實際的列名會引發錯誤? 是否需要先將其轉換為字符串或其他內容?

必須有采用整數值的列,對於這些行,這是“無效比較”。 因此,只需檢查它是否為str的實例即可。

for col,row in d.iteritems():
    if isinstance(row[0], str):
        d.loc[d[col] == 'No', col] = 0
        d.loc[d[col] == 'Yes', col] = 1

並且出於同樣的原因

d.loc[d['Combined'] == 'No', 'Combined'] = 0

這是完美的工作,因為它已經是帶有字符串值的列。

暫無
暫無

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

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