缺失值的归因和它们的划分

Imputation of missing values and division of those

想象一个如下所示的数据集:

df = pd.DataFrame({'Contacts 6M':[4,7,20,5,6,0,1,19], 'Contacts 3M':[2,3,9,np.nan,np.nan,0,np.nan,9]})

如你所想:第'Contacts 6M'列是最近6个月的联系人数统计,另一列是最近3个月的联系人数信息。所以'Contacts 3M'包含了另一列的部分信息。

我使用正向填充方法来估算缺失值:

df.ffill(轴 = 1,就地=真)

我的问题:如何在遍历数据集时将估算值除以 2 并四舍五入估算值(请不要使用浮点数)?

你可以跟踪你有 np.nan 的索引,然后用它做你想做的任何算术-

import pandas as pd
import numpy as np

df = pd.DataFrame({'Contacts 6M': [4, 7, 20, 5, 6, 0, 1, 19], 'Contacts 3M': [2, 3, 9, np.nan, np.nan, 0, np.nan, 9]}, dtype=np.int)
mask = df['Contacts 3M'].isna()

df = df.ffill(axis=1)  # for some weird reason, inplace=True was throwing 'NotImplementedError'
df['Contacts 3M'][mask] //= 2

print(df)
输出
   Contacts 6M  Contacts 3M
0            4            2
1            7            3
2           20            9
3            5            2
4            6            3
5            0            0
6            1            0
7           19            9

通过这种方式很容易做到:

df.iloc[df[df['Contacts 3M'].isna()].index,1]=df[df['Contacts 3M'].isna()]['Contacts 6M']/2

df['Contacts 3M']=df['Contacts 3M'].astype('int')