我有以下pandas.core.series.Series
:
Color
Red 4
Green 7
以及下面的多索引数据帧。我的目标是在dataframe中创建Target
列,方法是检查dataframe中的Value
列是否小于pandas.core.series.Series
中相应的颜色值,如果是这样,则返回1。例如,在第一行中,dataframe中Value
列中的值是12,这比pandas series对象中对应的匹配索引值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
而不是运算符,并指定轴。你知道吗lt
=“小于”相关问题 更多 >
编程相关推荐