如何根据其他列的条件在数据框中创建新列?

2024-05-18 07:14:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样一个数据框:

                             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

我想根据其他两列的条件创建第三列,其中包含3个可能的类。我试着在下面写一个函数,但它不起作用-我调用时没有得到返回测向头()调用函数后。你知道吗

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个类,但我是一个新手,所以可能不会得到它。你知道吗


Tags: 数据函数dfvaluedef条件timestampstate
1条回答
网友
1楼 · 发布于 2024-05-18 07:14:35

首先,设置您的条件:

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,因为在本例中,虽然它同时具有TransactionIdValue,但它显示为Vacant,因为没有上一行。你知道吗

一个可能的选择是假设一个设备有ValueTransactionID,它已经开始充电,我们可以使用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

相关问题 更多 >