![](/img/trans.png)
[英]How to replace all non-NaN entries of a dataframe with 1 and all NaN with 0
[英]How to Replace All the “nan” Strings with Empty String in My DataFrame?
我的數據幀中散布着"None"
和"nan"
字符串。 有沒有辦法用空字符串""
或nan
替換所有這些,所以當我將數據幀導出為excel表時它們不顯示?
簡化示例:
注意: col4
中的nan
不是字符串
ID col1 col2 col3 col4
1 Apple nan nan nan
2 None orange None nan
3 None nan banana nan
在我們用空字符串""
替換它們之后刪除所有"None"
和"nan"
字符串后,輸出應該是這樣的:
ID col1 col2 col3 col4
1 Apple nan
2 orange nan
3 banana nan
知道如何解決這個問題嗎?
謝謝,
使用一個字符串列表替換為不會影響實際nan
的空白字符串...
df.replace(['nan', 'None'], '')
哪個會給你一個新的數據幀:
ID col1 col2 col3 col4
1 Apple NaN
2 orange NaN
3 banana NaN
您可以將每個列與numpy對象dtype(基本上是文本列)進行比較,然后只對這些列進行替換。
for col in df:
if df[col] == np.dtype('O'): # Object
df.col1.replace(['None', 'NaN', np.nan], "", inplace=True)
所有這些環路解調解決方案......
replacers = [None, np.nan, "None", "NaN", "nan"] # and everything else that needs replacing.
df.loc[:, df.dtypes == 'object'].replace(replacers, '', inplace=True)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.