gpt4 book ai didi

python - 划分两个 pandas DataFrames 并保留非数字列

转载 作者:太空狗 更新时间:2023-10-30 02:53:28 25 4
gpt4 key购买 nike

我有两个包含数值和非数值的 pandas DataFrame。我想将一个除以另一个,但保留非数字列。这是一个 MWE:

a = pd.DataFrame(
[
['group1', 1., 2.],
['group1', 3., 4.],
['group1', 5., 6.]
],
columns=['Group', 'A', 'B']
)

b = pd.DataFrame(
[
['group1', 7., 8.],
['group1', 9., 10.],
['group1', 11., 12.]
],
columns=['Group', 'A', 'B']
)

尝试做:

b.div(a)

结果:

TypeError: unsupported operand type(s) for /: 'str' and 'str'

为了解决这个问题,我做了:

result = b.drop(["Group"], axis=1).div(a.drop(["Group"], axis=1))
print(result)
# A B
#0 7.0 4.0
#1 3.0 2.5
#2 2.2 2.0

这是正确的,但我还想保留 “Group” 列。

获得我想要的输出的一种方法是:

desired_output = b[["Group"]].join(result)
print(desired_output)
# Group A B
#0 group1 7.0 4.0
#1 group1 3.0 2.5
#2 group1 2.2 2.0

但我的真实 DataFrame 有许多非数字列。有没有一种更干净/更快/更有效的方法来告诉 pandas 只划分数字列?

最佳答案

您可以使用 np.divide,将掩码传递给 where 参数。

np.divide(b, a, where=a.dtypes.ne(object))

假设非数字列在 DataFrame 中是相同的,使用 combine_first/fillna 来取回它们:

np.divide(b, a, where=a.dtypes.ne(object)).combine_first(a)


Group A B
0 group1 7.0 4.0
1 group1 3.0 2.5
2 group1 2.2 2.0

关于python - 划分两个 pandas DataFrames 并保留非数字列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49412694/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com