如何用另一列的模式正确地填充这些NaN值?

2024-04-19 13:01:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习如何处理数据集中丢失的值。我有一张表,里面有大约一百万个条目。我正在尝试处理少量丢失的值。在

我的数据与自行车共享系统有关,缺少的值是起始位置和结束位置。在

资料图:缺少起点,只有7个数值

enter image description here

资料图:缺少终点站,共24个值

enter image description here

我想在这两种情况下用“相反”站的模式填充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和{}列并将{}替换为免费电台的相应模式的正确方法是什么?在


Tags: 数据dfindexmode系统模式自行车条目
1条回答
网友
1楼 · 发布于 2024-04-19 13:01:41

在我看来,当您希望像这样迭代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)

相关问题 更多 >