Was*_*uel 5 python dataframe python-3.x pandas categorical-data
我在数据框中有一列有分类数据,但缺少一些数据,即NaN.我想对这些数据进行线性插值以填补缺失值,但我不确定如何去做.我不能删除NaN来将数据转换为分类类型,因为我需要填充它们.一个简单的例子来演示我想要做什么.
col1 col2
5 cloudy
3 windy
6 NaN
7 rainy
10 NaN
Run Code Online (Sandbox Code Playgroud)
假设我想转换 col2为分类数据但保留NaN并使用线性插值填充它们我该如何处理它.让我们说在将列转换为分类数据后,它看起来像这样
col2
1
2
NaN
3
NaN
Run Code Online (Sandbox Code Playgroud)
然后我可以做线性插值并得到这样的东西
col2
1
2
3
3
2
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
更新:
有没有办法在插值后将数据转换回原始形状,而不是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
Run Code Online (Sandbox Code Playgroud)
旧的"数字"答案:
IIUC你可以这样做:
In [66]: df
Out[66]:
col1 col2
0 5 cloudy
1 3 windy
2 6 NaN
3 7 rainy
4 10 NaN
Run Code Online (Sandbox Code Playgroud)
首先让我们分解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
Run Code Online (Sandbox Code Playgroud)
现在我们可以插入它(用-1's 替换NaN's):
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
Run Code Online (Sandbox Code Playgroud)
相同的方法,但将插值系列转换为categorydtype:
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]
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3023 次 |
| 最近记录: |