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)
添加回答
举报
