[英]Replace numeric values in a pandas dataframe
問題 :污染的數據框。
詳細信息:框架由我知道的NaN字符串值和數字值組成。
任務 :用NaN替換數值
例
import numpy as np
import pandas as pd
df = pd.DataFrame([['abc', 'cdf', 1], ['k', 'sum', 'some'], [1000, np.nan, 'nothing']])
出:
0 1 2
0 abc cdf 1
1 k sum some
2 1000 NaN nothing
嘗試1 (無效,因為正則表達式僅查看字符串單元格)
df.replace({'\d+': np.nan}, regex=True)
出:
0 1 2
0 abc cdf 1
1 k sum some
2 1000 NaN nothing
初步解決方案
val_set = set()
[val_set.update(i) for i in df.values]
def dis_nums(myset):
str_s = set()
num_replace_dict = {}
for i in range(len(myset)):
val = myset.pop()
if type(val) == str:
str_s.update([val])
else:
num_replace_dict.update({val:np.nan})
return str_s, num_replace_dict
strs, rpl_dict = dis_nums(val_set)
df.replace(rpl_dict, inplace=True)
出:
0 1 2
0 abc cdf NaN
1 k sum some
2 NaN NaN nothing
問題是否有更簡單/更愉快的解決方案?
您可以對str
進行一次str
以替換值並返回。
df.astype('str').replace({'\d+': np.nan, 'nan': np.nan}, regex=True).astype('object')
#This makes sure already existing np.nan are not lost
輸出量
0 1 2
0 abc cdf NaN
1 k sum some
2 NaN NaN nothing
您可以使用循環遍歷每列,並檢查每一項。 如果它是整數或浮點數,則將其替換為np.nan。 使用列上的地圖功能可以輕松完成此操作。
您可以更改if
的條件以合並所需的任何數據類型。
for x in df.columns:
df[x] = df[x].map(lambda item : np.nan if type(item) == int or type(item) == float else item)
這是一個幼稚的方法,必須有比這更好的解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.