【发布时间】: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
【问题讨论】: