gpt4 book ai didi

python - 将不同的 Pandas 数据框与系列对象进行比较

转载 作者:太空宇宙 更新时间:2023-11-04 08:31:55 25 4
gpt4 key购买 nike

我有以下 pandas.core.series.Series:

Color
Red 4
Green 7

还有以下多索引数据框。我的目标是通过检查数据框中的 Value 列是否小于 pandas.core 中的相应颜色值来在数据框中创建 Target 列。 series.Series 如果是这样则返回 1。例如,在第一行中,dataframe 中 Value 列中的值为 12,这比 pandas 系列对象中对应的匹配索引值 4 大,因此 Target 返回 0。

              Value    Target
Color Animal
Red Tiger 12 0
Tiger 3 1
Green Lion 6 1
Lion 35 0

我的以下尝试得到一个 ValueError: Can only compare identically-labeled Series objects

import pandas as pd
import numpy as np
x = pd.Series([4,7], index=['Red','Green'])
x.index.name = 'Color'

dt = pd.DataFrame({'Color': ['Red','Red','Green','Green'], 'Animal': ['Tiger','Tiger','Lion','Lion'], 'Value': [12,3,6,35]})
dt.set_index(['Color','Animal'], inplace=True)
dt['Target'] = np.where(dt['Value'] < x ,1 ,0 )

最佳答案

使用 lt 代替运算符,并指定轴。

dt['Target'] = dt['Value'].lt(x, axis=0).astype(int)
print (dt)
Value Target
Color Animal
Red Tiger 12 0
Tiger 3 1
Green Lion 6 1
Lion 35 0

lt = "小于"

关于python - 将不同的 Pandas 数据框与系列对象进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52249017/

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