1 回答

TA貢獻(xiàn)1982條經(jīng)驗 獲得超2個贊
主要問題是regex=True默認(rèn)參數(shù)(pat
適用于正則表達(dá)式)。只需將參數(shù)設(shè)置為或者您可以使用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
更新。 對于更好地與自定義函數(shù)一起使用的不同計算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)
添加回答
舉報