简体   繁体   English

逐列填充模式

[英]Fillna with mode column by column

I got some like this: x: Users y: Ratings我得到了一些这样的: x:用户 y:评级

and this shows user 1 rating movie 1 with 4.0 user 1 not rating movie 2 user 1 rating movie 3 with 1.0 and so这显示用户 1 用 4.0 评价电影 1 用户 1 不评价电影 2 用户 1 用 1.0 评价电影 3 等等

       rating
movieId 1      2      3      4     5   .....
userID
1      4.0    NaN     1.0   4.1    NaN
2      NaN      2     5.1   NaN    NaN
3      3.0    2.0     NaN   NaN    NaN
4      5.0    NaN     2.8   NaN    NaN

How could I fill NaN values with mode by Movie如何通过 Movie 使用模式填充 NaN 值

example movieId 1 has ratings 4.0, NaN, 3.0, 5.0..... then fill NaNs with 4.0(mode) i tried to use fillna示例movieId 1 的评分为4.0、NaN、3.0、5.0 ..... 然后用4.0(模式)填充NaN 我尝试使用fillna

rating.apply(lambda x: x.fillna(x.mode().item()))

Try尝试

rating.apply(lambda x: x.fillna(x.mode()), axis=0)

specify axis=0指定axis=0

Alternatively,或者,

import numpy as np
import pandas as pd

def fillna_mode(df, cols_to_fill):
    for col in cols_to_fill:
        df[col].fillna(df[col].mode()[0], inplace=True)

sample = {1: [4.0, np.nan,1.0, 4.1, np.nan],
          2: [np.nan, 2, 5.1, np.nan, np.nan]}

rating = pd.DataFrame(sample)
print(rating)
      1 2
0   4.0 NaN
1   NaN 2.0
2   1.0 5.1
3   4.1 NaN
4   NaN NaN
fillna_mode(rating, [1, 2])

Output Output

    1   2
0   4.0 2.0
1   1.0 2.0
2   1.0 5.1
3   4.1 2.0
4   1.0 2.0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM