簡體   English   中英

如何從數據框中刪除具有空值和分類變量的行?

[英]How can I drop the rows with null values and categorical variables from the dataframe?

我試圖從我從 Excel 導入的數據框中刪除具有空值和分類變量的行。 我已經嘗試了許多其他功能和許多不同的方法來這樣做,但我無法刪除它們,至少不是全部。

大約有 185000 行和 6 列。 我試圖做的是使用 for 循環遍歷整行並在“訂單 ID”列上有空值或分類變量時刪除行。

這是我嘗試過的代碼之一:

f = 0

value = merged_file.at[f, 'Order ID']
for value in merged_file:
    if value is None:
        merged_file.drop(merged_file.index[f])
        merged_file.reset_index(inplace=True, drop=True)
        f+=1
        continue
    elif value == 'Order ID':
        merged_file.drop(merged_file.index[f])
        merged_file.reset_index(drop=True, inplace=True)
        f+=1
        continue
    elif f==186845:
        break
    else:
        f+=1
        continue

如果糾正我做錯了什么,我將不勝感激,如果有更好的方法來指定和刪除具有空值和分類變量的行或列,請告訴我。

謝謝你。

因此,即使代碼看起來不是真正的 Pythonic,您似乎也在使用 Pandas。 無論如何,我建議不要遍歷數據幀的每一行,在包含 nan 的熊貓行中可以使用dropna 刪除

 merged_file.dropna(subset=['Order ID'],inplace=True)

要刪除包含分類變量的行,您可以使用 numpy isreal Apply 簡單地將函數 isreal 應用於所有行,將所有不包含數值的行標記為 False。

import numpy as np
merged_file = merged_file[merged_file['Order ID'].apply(lambda x: np.isreal(x))]

暫無
暫無

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

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