UPDATE:
是否有辦法後 插即代替1,2或3的數據轉換回其原來的形式,你有陰天,大風多雨 一遍嗎?
解決方案:我有意添加更多的行原來的DF:
In [129]: df
Out[129]:
col1 col2
0 5 cloudy
1 3 windy
2 6 NaN
3 7 rainy
4 10 NaN
5 5 cloudy
6 10 NaN
7 7 rainy
In [130]: df.dtypes
Out[130]:
col1 int64
col2 category
dtype: object
In [131]: df.col2 = (df.col2.cat.codes.replace(-1, np.nan)
...: .interpolate().astype(int).astype('category')
...: .cat.rename_categories(df.col2.cat.categories))
...:
In [132]: df
Out[132]:
col1 col2
0 5 cloudy
1 3 windy
2 6 rainy
3 7 rainy
4 10 cloudy
5 5 cloudy
6 10 cloudy
7 7 rainy
OLD 「數字」 的答案:
IIUC你可以這樣做:
In [66]: df
Out[66]:
col1 col2
0 5 cloudy
1 3 windy
2 6 NaN
3 7 rainy
4 10 NaN
首先讓我們分解一下col2
:
In [67]: df.col2 = pd.factorize(df.col2, na_sentinel=-2)[0] + 1
In [68]: df
Out[68]:
col1 col2
0 5 1
1 3 2
2 6 -1
3 7 3
4 10 -1
現在我們可以估算出它('與NaN
小號的更換-1
):
In [69]: df.col2.replace(-1, np.nan).interpolate().astype(int)
Out[69]:
0 1
1 2
2 2
3 3
4 3
Name: col2, dtype: int32
同樣的方法,但插值系列轉換爲category
D型:
In [70]: df.col2.replace(-1, np.nan).interpolate().astype(int).astype('category')
Out[70]:
0 1
1 2
2 2
3 3
4 3
Name: col2, dtype: category
Categories (3, int64): [1, 2, 3]
完美的作品。有沒有一種方法可以在插值後將數據轉換回原始形式,即不是1,2或3,而是再次出現「陰天」,「多風」和「雨天」? –
@WasswaSamuel,我已經更新了我的答案 - 請檢查 – MaxU
通過查看這些答案,可以學到多少知識。今天回家分解()和插值():) – Vaishali