在for循环中使用Regex搜索数据帧,以提取与Regex关联的值



我有一个来自更大数据帧的子集数据帧。我需要能够创建一个for循环,该循环搜索数据帧并提取与正确名称相对应的数据。

import pandas as pd
import numpy as np
import re
data = {'Name': ['CH_1', 'CH_2', 'CH_3', 'FV_1', 'FV_2', 'FV_3'],
'Value': [1, 2, 3, 4, 5, 6]
}
df = pd.DataFrame(data)
FL = [17.7, 60.0]
CH = [20, 81.4]
tol = 8
time1 = FL[0] + tol
time2 = FL[1] + tol
time3 = CH[0] + tol
time4 = CH[1] + tol
FH_mon = df['Values'] *5
workpercent = [.7, .92, .94]
mhpy = [2087, 2503, 3128.75]
list1 = list()
list2 = list()
for x in df['Name']:
if x == [(re.search('FV_', s)) for s in df['Name'].values]:
y = np.select([FH_mon < time1 , (FH_mon >= time1) and (FH_mon < time2), FH_mon > time2], [workpercent[0],workpercent[1],workpercent[2]])
z = np.select([FH_mon < time1 , (FH_mon >= time1) and (FH_mon < time2), FH_mon > time2], [mhpy[0],mhpy[1],mhpy[2]])   
if x == [(re.search('CH_', s)) for s in df['Name'].values]:
y = np.select([FH_mon < time3, (FH_mon >= time3) and (FH_mon < time4)],  [workpercent[0],workpercent[1]])
z = np.select([FH_mon < time3, (FH_mon >= time3) and (FH_mon < time4)],  [mhpy[0],mhpy[1]])
list1.append(y)
list2.append(z)

我之前有一个简单的版本,只添加了几个数字,我得到了非常有用的答案来回答我的问题,但这里是更复杂的版本。我需要搜索,只要name列中有FV,if循环就会运行并使用带有FV的name列中的数据。CH也是如此。当循环循环通过Name列时,我有列表来跟踪每个值。如果有一种更简单的方法,我真的很高兴看到它,但现在这似乎是最干净的方法,但我收到了错误,否则循环将无法正常工作。

这应该是您想要的:

for index, row in df.iterrows(): 
if re.search("FV_", row["Name"]): 
df.loc[index, "Value"] += 2 
elif re.search("CH_", row["Name"]): 
df.loc[index, "Value"] += 4

如果;名称";列仅具有以"0"开头的值;FV_;或";CH_";,使用where:

df["Value"] = df["Value"].add(2).where(df["Name"].str.startswith("FV_"), df["Value"].add(4))

如果在";名称";,使用numpy.select:

import numpy as np
df["Value"] = np.select([df["Name"].str.startswith("FV_"), df["Name"].str.startswith("CH_")], [df["Value"].add(2), df["Value"].add(4)])
输出:
>>> df
Name  Value
0  CH_1      5
1  CH_2      6
2  CH_3      7
3  FV_1      6
4  FV_2      7
5  FV_3      8

最新更新