TransactionId Value
Timestamp
2018-01-07 22:00:00.000 633025 674.87
2018-01-07 22:15:00.000 633025 676.11
2018-01-07 22:30:00.000 633025 677.06
我想根据其他2列的条件创建具有3个可能的类的第三列.我尝试在下面编写函数,但无法正常工作-调用函数后调用df.head()时没有得到回报.
b = df.shape[0]
def charger_state(df):
a = 1
while a <= b:
if df.Value[a]-df.Value[(a-1)] > 0.1 :
df['Charger State']= "Charging"
elif df.Value[a]-df.Value[(a-1)] < 0.1 \
and df['TransactionId'] > 0:
df['Charger State']= "Not Charging"
else:
df['Charger State']= "Vacant"
a = a+1
围绕该主题的其他答案似乎并未涵盖新专栏的3个类,但我是新手,因此可能无法理解.
解决方法:
首先,设置您的条件:
c1 = df.Value.sub(df.Value.shift()).gt(0.1)
c2 = df.Value.diff().lt(0.1) & df.TransactionId.gt(0)
现在使用np.select:
df.assign(ChargerState=np.select([c1, c2], ['Charging', 'Not Charging'], 'Vacant'))
TransactionId Value ChargerState
Timestamp
2018-01-07 22:00:00 633025 674.87 Vacant
2018-01-07 22:15:00 633025 676.11 Charging
2018-01-07 22:30:00 633025 677.06 Charging
您可能需要调整c1,因为在此示例中,尽管它同时具有TransactionId和Value,但由于没有上一行而显示为Vacant.
一种可能的选择是假设如果设备具有Value和TransactionID,则它已开始收费,这可以在c1上使用fillna完成:
c1 = df.Value.sub(df.Value.shift().fillna(0)).gt(0.1) # Notice the fillna
c2 = df.Value.diff().lt(0.1) & df.TransactionId.gt(0)
df.assign(ChargerState=np.select([c1, c2], ['Charging', 'Not Charging'], 'Vacant'))
TransactionId Value ChargerState
Timestamp
2018-01-07 22:00:00 633025 674.87 Charging
2018-01-07 22:15:00 633025 676.11 Charging
2018-01-07 22:30:00 633025 677.06 Charging