我有一个大约600,000行的数据集.由于使用了pandas iterrow(),以下代码需要很长时间才能运行.是否有适用于下面所示特定代码的替代方案

%%time
import numpy as np
df_inputed = df # dataframe with many missing values
for index, row in df_to_inpute.iterrows(): 
    sic = row['sic']
    year = row['year']
    quarter = row['quarter']
    for col in cols_to_check: #columns except for date and pk columns
        value = row[col]
        if np.isnan(value): 
            median = get_median(sic, year, quarter) #assume operation is O(1) time
            if not np.isnan(median): 
                df_inputed.at[index, col] = median

推荐答案

结合df.apply+pd.Series.fillna种方法:

def fill_with_median(x):
    if x[cols_to_check].isna().any():  # if filling is needed
        med = x[cols_median].median()
        if not np.isnan(med):
            x[cols_to_check] = x[cols_to_check].fillna(med)
    return x

cols_median = ['sic', 'year', 'quarter']

df = df.apply(fill_with_median, axis=1)

另一种方法是使用boolean masks过滤所需的切片以进行填充:

m = df[cols_to_check].isna().any(axis=1)
med_vals = df[cols_median][m].median(1)
df.loc[m & med_vals.notna(), cols_to_check] = med_vals

Python-3.x相关问答推荐

使用Python装载. iso文件

为什么打印语句在Python多处理脚本中执行两次?

CONNEXION.EXCEPTIONS.ResolverError:运行pyz文件时未命名模块

TypeError:&Quot;Value&Quot;参数必须是标量、Dict或Series,但您传递了&Quot;Index&Quot;

是什么原因导致Pandas=2.1.4和Pandas=1.4.2之间Pandas DataFrame中从Float64到int32的连续列转换方式不同

Pyvis和Networkx:如何根据源或目标使 node colored颜色 不同

为什么我的Selenium脚本在密码元素上失败?

新行是pandas数据帧中旧行的组合

检测点坐标 - opencv findContours()

使用 iloc 或 loc 对多列进行过滤

从一列字符串中提取子字符串并将它们放入列表中

如何确保 GCP Document AI 模型输出与输入文件同名的 JSON?

使用 python 查找标记的元素

SMTP 库 Python3:不太安全的应用程序访问

非拉丁字符的Python正则表达式不起作用

如何使用 Selenium by class_name 从大学橄榄球数据中抓取图像 url 列表

Pandas 将列格式化为货币

变量类型注解NameError不一致

警告:请使用 tensorflow/models 中的官方/mnist/dataset.py 等替代方案

pdfminer python 3.5