【问题标题】:Conditional data imputation in PythonPython中的条件数据插补
【发布时间】:2020-08-26 00:16:08
【问题描述】:

我正在尝试有条件地估算我的数据集中的值。

假设我有三列,如果第 1 列为 1,则第 2 列为 0,第 3 列为 0;如果第 1 列是 2,那么第 2 列是 Mean (),第 3 列是 Mean()。

我尝试使用函数 any() 运行 if 语句并分别定义条件。

但是,根据条件没有满足条件,我要么得到所有平均值,要么得到全零。

具体代码如下:

if (df['Retention_Term'] == 6):
    df.cl_tot_calls_term_seq_1.replace(999, np.nan,inplace = True)
df['cl_tot_calls_term_seq_1'].fillna(df['cl_tot_calls_term_seq_1'].median(),inplace= True)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

【问题讨论】:

  • 你能包括其余的堆栈跟踪吗? (如果我完全了解 pandas,我可能会弄清楚发生了什么,但对我来说,这些函数中的哪一个需要 bool 并得到一个 `Series 并不明显。)

标签: python-3.x pandas valueerror


【解决方案1】:

像这样试试。

mask1 = df['Retention_Term']==6
mask2 = df['cl_tot_calls_term_seq_1'] == 999 
df.loc[mask1 & mask2, 'cl_tot_calls_term_seq_1'] = np.nan

那么其余的应该没问题。

df['cl_tot_calls_term_seq_1'].fillna(df['cl_tot_calls_term_seq_1'].median(), inplace= True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-21
    • 2020-10-08
    • 1970-01-01
    • 2013-06-17
    • 1970-01-01
    • 2020-04-19
    • 2020-04-04
    • 1970-01-01
    相关资源
    最近更新 更多