我正在使用 JupyterLab 和 Anaconda。
我有 2 个类似的数据框。我想将一个数据帧的(部分/子集)除以(的部分/子集),然后更新原始数据帧。以下是我写的代码:
def f_test_df(n_rows, n_cols):
df_local = pd.DataFrame(np.random.rand(n_rows, n_cols))
df = df_local.applymap(lambda x: round(x*10))
return df
np.random.seed(seed=1)
df1 = f_test_df(4, 4)
df1.rename(columns={0:'test'}, inplace=True)
df2 = f_test_df(4, 4)
df2.rename(columns={0:'test'}, inplace=True)
df_div = df1.iloc[:, 1:].div(df2.iloc[:, 1:])
minimum_value = 2
display(df1)
display(df2)
display(df_div)
df1.iloc[:, 1:].replace(df_div, inplace=True)
df1
我希望 df1 由获得的除法 (df_div) 更新。从输出中可以看出,df1 没有更新。我应该如何纠正除法过程?
答案 0 :(得分:1)
我认为最简单的是分配回来:
df1.iloc[:, 1:] = df1.iloc[:, 1:].div(df2.iloc[:, 1:])
print(df1)
test 1 2 3
0 4 1.166667 0.000000 1.500000
1 1 0.100000 0.666667 0.428571
2 4 0.555556 4.000000 inf
3 2 1.000000 0.000000 1.750000