[英]How to replace every NaN in a column with different random values using pandas?
我最近一直在玩大熊貓,現在我嘗試用不同的正態分布隨機值替換數據幀內的NaN值。
假設我有沒有標題的CSV文件
0
0 343
1 483
2 101
3 NaN
4 NaN
5 NaN
我的預期結果應該是這樣的
0
0 343
1 483
2 101
3 randomnumber1
4 randomnumber2
5 randomnumber3
但相反,我得到以下內容:
0
0 343
1 483
2 101
3 randomnumber1
4 randomnumber1
5 randomnumber1 # all NaN filled with same number
我的代碼到目前為止
import numpy as np
import pandas as pd
df = pd.read_csv("testfile.csv", header=None)
mu, sigma = df.mean(), df.std()
norm_dist = np.random.normal(mu, sigma, 1)
for i in norm_dist:
print df.fillna(i)
我想從數據幀中獲取NaN行的數量, np.random.normal(mu, sigma, 1)
的數字1替換為NaN行的總數,以便每個NaN可能具有不同的值。
但是我想問一下是否有其他簡單方法可以做到這一點?
感謝您的幫助和建議。
這是使用底層數組數據的一種方法 -
def fillNaN_with_unifrand(df):
a = df.values
m = np.isnan(a) # mask of NaNs
mu, sigma = df.mean(), df.std()
a[m] = np.random.normal(mu, sigma, size=m.sum())
return df
本質上,我們使用帶有np.random.normal
的大小參數np.random.normal
生成所有隨機數和NaN的計數,並再次使用NaN的掩碼一次性分配它們。
樣品運行 -
In [435]: df
Out[435]:
0
0 343.0
1 483.0
2 101.0
3 NaN
4 NaN
5 NaN
In [436]: fillNaN_with_unifrand(df)
Out[436]:
0
0 343.000000
1 483.000000
2 101.000000
3 138.586483
4 223.454469
5 204.464514
我想你需要:
mu, sigma = df.mean(), df.std()
#get mask of NaNs
a = df[0].isnull()
#get random values by sum ot Trues, processes like 1
norm_dist = np.random.normal(mu, sigma, a.sum())
print (norm_dist)
[ 184.90581318 364.89367364 181.46335348]
#assign values by mask
df.loc[a, 0] = norm_dist
print (df)
0
0 343.000000
1 483.000000
2 101.000000
3 184.905813
4 364.893674
5 181.463353
在pandas DataFrame列中輸入隨機值代替缺失值很簡單。
mean = df['column'].mean()
std = df['column'].std()
def fill_missing_from_Gaussian(column_val):
if np.isnan(column_val) == True:
column_val = np.random.normal(mean, std, 1)
else:
column_val = column_val
return column_val
現在只需將上述方法應用於缺少值的列。
df['column'] = df['column'].apply(fill_missing_from_Gaussian)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.