我有一個資料集,其中一些缺失值為“?” 在僅一列中,我想用該列(Feature1)中的其他值替換所有缺失值,如下所示:
Feature1_value_counts = df.Feature1.value_counts(normalize=True)
上面的代碼給了我可以在 pandas Feature1 中用于 frac 的數字,它包含 15 組唯一值,所以它有 15 個數字(所有百分比)
現在我只需要隨機替換“?”s 用那些唯一值(所有字串)和那個分數概率
我不知道如何使用熊貓來做到這一點!
我已經嘗試過 loc() 和 iloc() 以及一些 for 和 ifs 我無法到達那里
uj5u.com熱心網友回復:
您可以利用以下p引數numpy.random.choice:
import numpy as np
# ensure using real NaNs for missing values
df['Feature1'] = df['Feature1'].replace('?', np.nan)
# count the fraction of the non-NaN value
counts = df['Feature1'].value_counts(normalize=True)
# identify the rows with NaNs
m = df['Feature1'].isna()
# replace the NaNs with a random values with the frequencies as weights
df.loc[m, 'Feature1'] = np.random.choice(counts.index, p=counts, size=m.sum())
print(df)
輸出(為清楚起見,將值替換為大寫):
Feature1
0 a
1 b
2 a
3 A
4 a
5 b
6 B
7 a
8 A
使用的輸入:
df = pd.DataFrame({'Feature1': ['a', 'b', 'a', np.nan, 'a', 'b', np.nan, 'a', np.nan]})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/532879.html
