簡體   English   中英

使用 for 循環替換 Pandas 中每一行和每一列的單元格值

[英]Replace cell values for each row and each column in Pandas using for loop

我將 python 與 pandas 一起使用,但也可以導入任何其他庫 Mu 數據集在每列的數千行中具有缺失值 (NaN)。

例子

**Name,Type,Region...**
Oranges,Fruit,Western Europe  
NaN,NaN,NaN  
NaN,NaN,NaN  
Blueberry, berry,Easter Europe  
NaN,NaN,NaN 
Raspberry, berry,Easter Europe
NaN,NaN,NaN
NaN,NaN,NaN 

我們可以假設具有 NaN 的單元格中的值可以重寫為與先前的值相同,直到達到新的非 NaN 值。 例子:

**Name,Type,Region...**
Oranges,Fruit,Western Europe  
Oranges,Fruit,Western Europe 
Oranges,Fruit,Western Europe 
Blueberry, berry,Easter Europe  
Blueberry, berry,Easter Europe 
Raspberry, berry,Easter Europe  
Raspberry, berry,Easter Europe  
Raspberry, berry,Easter Europe

如何遍歷每一行值和每一列以重寫 NaN 值以匹配它之前的第一個非 NaN 值?

規則:如果 cell = NaN 且 previous_cell = not NaN,則將值替換為 previous_cell,如果 cell = NaN 且 previous_cell = NaN,則繼續(消除整列為空時的邊緣情況)如果 cell = NaN,則繼續

我有一個巨大的數據集,所以這不可能在 CSV 文件本身中手動完成

嵌套查詢不起作用

您可以將 apply 與 ffill 一起用於 pandas 中可用的所有 clomuns:

df.apply(lambda x: x.fillna(df['Name'].shift())).ffill()
df.apply(lambda x: x.fillna(df['Type'].shift())).ffill()
df.apply(lambda x: x.fillna(df['Region'].shift())).ffill()

暫無
暫無

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

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