我正在学习如何处理数据集中丢失的值。我有一张表,里面有大约一百万个条目。我正在尝试处理少量丢失的值。在
我的数据与自行车共享系统有关,缺少的值是起始位置和结束位置。在
资料图:缺少起点,只有7个数值
资料图:缺少终点站,共24个值
我想在这两种情况下用“相反”站的模式填充NaN
。例如,对于start_station==21
,我想看看最常见的end_station
,并用它来填充我缺少的值。
E、 g.df.loc[df['start_station'] == 21].end_station.mode()
我试图用一个函数来实现:
def inpute_end_station(df):
for index, row in df.iterrows():
if pd.isnull(df.loc[index, 'end_station']):
start_st = df.loc[index, 'start_station']
mode = df.loc[df['start_station'] == start_st].end_station.mode()
df.loc[index, 'end_station'].fillna(mode, inplace=True)
最后一行抛出一个AttributeError: 'numpy.float64' object has no attribute 'fillna'
。如果我只使用df.loc[index, 'end_station'] = mode
我得到ValueError: Incompatible indexer with Series
。在
我处理这个问题合适吗?我知道修改pandas中迭代的内容是不好的做法,那么更改start_station
和{
在我看来,当您希望像这样迭代pandas中的列时,最佳实践是使用
apply()
函数。在对于这种特殊情况,我建议使用以下方法,这在下面的示例数据中显示。我没有太多经验使用
mode()
方法,所以我使用value_counts()
方法和first_valid_index()
方法来确定模式值。在相关问题 更多 >
编程相关推荐