【问题标题】:Faster Alternative to Iterrows() while looping through dataframe在循环数据帧时更快地替代 Iterrows()
【发布时间】:2021-03-03 02:39:00
【问题描述】:

我正在尝试从给定列的列表中找到循环遍历数据框并替换所有我想要的特定值的“nan”的替代方法。现在我正在使用非常慢的 iterrows,有没有替代方法?

基本上我所拥有的是一些带有 NAN 值的列,这些列应该只包含 1 或 0。所以我要做的是将每行中的 NAN 替换为每列中已经存在的 1 和 0 的百分比。假设 column_T 有 30% 的 1 和 70% 的 0,所以对于每次迭代我都想通过 randint() 条件,如果它小于 30% 的阈值,它将为该特定行输入 1,反之亦然0 对于每一个现有的 NAN 行,这将继续。

示例 Df.

Column_T Column_I
1 1
0 1
nan nan
1 0
nan 0
0 nan
1 1
for i, row in target_df.iterrows():
                for j in missing_col_list:
                    num_missing_obs = target_df[j].value_counts().sort_index()
                    chance_for_0s = (num_missing_obs[0]/(num_missing_obs[1]+num_missing_obs[0]))*100
                
                    #random assign 1s and 0s for missing data by calculated chance
                    if(str(row[j]) == 'nan'):
                        if (random.randint(0,100) < chance_for_0s): 
                            target_df.at[i,j] = 0.0
                        else:
                            target_df.at[i,j] = 1.0

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    这是使用pandas.Series.sample 的另一种方法:

    for col in df.columns:
        isnan = df[col].isna()
        df.loc[isnan, col] = df[col].dropna().sample(isnan.sum()).values
    

    【讨论】:

    • 如何根据 1 和 0 的百分比包含 if 条件???
    • @DavidLe 我利用了 sample 方法,因为它会根据原始比例返回 1 和 0
    • @DavidLe 我的意思是,我相信概率,所以我不需要 if
    猜你喜欢
    • 2018-12-11
    • 2021-08-20
    • 2022-07-06
    • 1970-01-01
    • 1970-01-01
    • 2018-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多