我有两个数据框,如 df1、df2。 在 df1 中,我有 4 列(A、B、C、D)和两行, 在 df2 中,我有 4 列(A、B、C、D)和两行。 现在我想减去两个数据帧,如 df1['A'] - df2['A'] 等等。但我不知道该怎么做。
df1-
df2 -
答案 0 :(得分:0)
只做减法但记住索引,例如,假设我有 df1
和 df2
具有相同的列但不同的索引:
df1 = dd.from_array(np.arange(8).reshape(2, 4), columns=['A','B','C','D'])
df2 = dd.from_pandas(pd.DataFrame(
np.arange(8).reshape(2, 4),
columns=['A','B','C','D'],
index=[1, 2]
), npartitions=1)
那么:
(df1 - df2).compute()
# A B C D
# 0 NaN NaN NaN NaN
# 1 4.0 4.0 4.0 4.0
# 2 NaN NaN NaN NaN
另一方面,让我们将 df2 的索引匹配到 df1 并减去
df2 = df2.assign(idx=1)
df2 = df2.set_index(df2.idx.cumsum() - 1)
df2 = df2.drop(columns=['idx'])
(df1 - df2).compute()
# A B C D
# 0 0 0 0 0
# 1 0 0 0 0