如何使用另一列的模式正确地估算这些 NaN 值?

How do I correctly impute these NaN values with modes of another column?

我正在学习如何处理数据集中的缺失值。我有一个 table 约 100 万个条目。我正在尝试处理少量缺失值。

我的数据涉及自行车共享系统,我的缺失值是起点和终点位置。

数据:缺少起始站,只有 7 个值

数据:终点站缺失,共24个值

我想把NaN两种情况都填成"opposite"站的模式。例如,对于 start_station==21,我想看看什么是最常见的 end_station,并用它来填充我的缺失值。 例如。 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_stationend_station 列并将 NaN 替换为相应内容的正确方法是什么免费站的模式?

在我看来,当您想像这样遍历 pandas 中的列时,最佳做法是使用 apply() 函数。

对于这种特殊情况,我建议采用以下方法,如下所示我的示例数据。我没有太多使用 mode() 方法的经验,所以我结合使用 value_counts() 方法和 first_valid_index() 方法来确定模式值。

# import pandas
import pandas as pd

# make a sample data
list_of_rows = [
  {'start_station': 1, 'end_station': 1},
  {'start_station': None, 'end_station': 1},
  {'start_station': 1, 'end_station': 2},
  {'start_station': 1, 'end_station': 3},
  {'start_station': 2, 'end_station': None},
  {'start_station': 2, 'end_station': 3},
  {'start_station': 2, 'end_station': 3},
]

# make a pandas data frame
df = pd.DataFrame(list_of_rows)

# define a function
def fill_NaNs_in_end_station(row):
    if pd.isnull(row['end_station']):
        start_station = row['start_station']
        return df[df['start_station']==start_station].end_station.value_counts().first_valid_index()
    return row['end_station']

# apply function to dataframe
df['end_station'] = df.apply(lambda row: fill_NaNs_in_end_station(row), axis=1)