为了账号安全,请及时绑定邮箱和手机立即绑定

从数据框中选择特定行并为新列执行计算

从数据框中选择特定行并为新列执行计算

慕桂英546537 2023-03-22 10:38:12
我有一个看起来像这样的数据框。       Task[ms]                              Funktion  ...     min     max  0        1              CALL_TK_CDDio_PFC_BEGIN_1MS  ...   0.640000   3.360000  1        1                       vAdcD_MainFunction  ...  21.280001  25.920000  2        1                          vPressE_Main1ms  ...  17.120001  81.279999  3        1  vPositionSensorPwm_MainFunction_Fast_In  ...   9.920000  13.760000  4        1                           CDDIO_1MS_1_IN  ...   2.240000   5.280000我必须选择与此列名称对应的行。有 146 行df['Messvariable']。这是数据框的 Messvariable 列0      timeslices[0].profilerDataProcess[0]_C0[us]1      timeslices[0].profilerDataProcess[1]_C0[us]2      timeslices[0].profilerDataProcess[2]_C0[us]3      timeslices[0].profilerDataProcess[3]_C0[us]4      timeslices[0].profilerDataProcess[4]_C0[us]                141    timeslices[9].profilerDataProcess[0]_C0[us]142    timeslices[9].profilerDataProcess[1]_C0[us]143    timeslices[9].profilerDataProcess[2]_C0[us]144    timeslices[9].profilerDataProcess[3]_C0[us]145    timeslices[9].profilerDataTask_C0[us]我想通过此列选择特定行并执行这样的操作 while  df['Messvariable'].str.contains("timeslices[1]"):   df['CPU_LOAD']=df['max']/(10000*2)并且对于具有不同计算的所有剩余时间片类似。这是行不通的。str.contains 返回空数据框。还有其他方法吗?
查看完整描述

1 回答

?
临摹微笑

TA贡献1982条经验 获得超2个赞

主要问题是regex=True默认参数(pat适用于正则表达式)。只需将参数设置为或者您可以使用orFalse来完成:startswith()find()


df = pd.DataFrame.from_dict({

    'Messvariable': ('timeslices[1]', 'timeslices[1]', 'empty', 'empty'),

    'max': (1, 2, 3, 4),

})


mask = df['Messvariable'].str.contains('timeslices[1]', regex=False)

# or

# mask = df['Messvariable'].str.find('timeslices[1]') != -1

# or

# mask = df['Messvariable'].str.startswith('timeslices[1]')

df['CPU_LOAD'] = 0

df.loc[mask, 'CPU_LOAD'] = df[mask]['max'] / (10000 * 2)

print(df.head())


#    Messvariable  max  CPU_LOAD

# 0  timeslices[1]    1   0.00005

# 1  timeslices[1]    2   0.00010

# 2          empty    3   0.00000

# 3          empty    4   0.00000

更新。 对于更好地与自定义函数一起使用的不同计算apply:


df['CPU_LOAD'] = 0


def set_cpu_load(x):

    if x['Messvariable'].startswith('timeslices[1]'):

        x['CPU_LOAD'] = x['max'] / (10000 * 2)

    elif x['Messvariable'].startswith('timeslices[2]'):

        pass  # other calculation

    # elif ...

    return x


df = df.apply(set_cpu_load, axis=1)




查看完整回答
反对 回复 2023-03-22
  • 1 回答
  • 0 关注
  • 144 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号