在熊猫中,如何检查两个字符串是否与现有数据框中的任何行中的多个列匹配并将其删除

时间:2019-02-03 21:27:41

标签: python pandas dataframe

我有一个看起来像这样的数据框

tableView(_ tableView: UITableView, 
         heightForRowAt indexPath: IndexPath) -> CGFloat

我将获得实时数据,该数据是一个rootID字符串,parentID字符串,jobID字符串和一个日期。

我想检查新检索到的rootID和parentID组合是否已存在于数据框中。因此,如果我检索rootID =“ A”和parentID ==“ B”,jobID ==“ T”,我想访问数据框的第一行。然后,我想删除该行并附加新信息并增加更新计数器。

result = []
def is_num(text):
    try:
        float(text)
        return True
    except:
        return False
with open('myfile', 'rw') as nf:
    lines = nf.readlines()
    for line in lines:
        line_list = line.split()
        for idx, item in enumerate(line_list):
            if is_num(item):
                result.append([item, line_list[idx-1])

数据框现在应类似于

                 rootID   parentID    jobID  time                         counter
              0    A         B          D    2019-01-30 14:33:21.339469      0
              1    E         F          G    2019-01-30 14:33:21.812381      0
              2    A         C          D    2019-01-30 15:33:21.812381      0
              3    E         B          F    2019-01-30 15:33:21.812381      0
              4    E         F          G    2019-01-30 16:33:21.812381      0

任何人都不知道该怎么做?

2 个答案:

答案 0 :(得分:1)

我会

root_id, parent_id, job_id = get_ids() # e.g. ('A', 'B', 'T')

cond = df.rootID.eq(root_id) & df.parentID.eq(parent_id) & df.jobID.eq(job_id)

df.loc[cond, ['time', 'counter']] = datetime.datetime.now(), df.loc[cond, 'counter']+1

这将更新您的数据框in_place。除非绝对需要,否则我不会一直对Dataframe进行重新排序。例如,如果您每天可以重新排序一次,则可以

df.sort_values(by='time') #.reset_index(drop=True), if needed

定期。但是,如果每次新数据到来时都必须更改行,那么假设您具有唯一的ID,

df = pd.concat([df[df[cond].index.item()+1:], df[cond]]) 

答案 1 :(得分:0)

我认为您可以通过翻译示例来获得非常接近的解决方案:

for index, row in df.iterrows():
    if row['rootID'] == rootID and row['parentID'] == parentID:
        df.drop(df.iloc[index])
        row['time'] = datetime.datetime.now()
        row['counter'] += 1
        df = df.concat(row)

无循环:

selected_row = df[(df['rootId'] == rootID) & (df['parentID'] == parentID)])
df.drop(selected_row)
selected_row['time'] = datetime.datetime.now()
selected_row['counter'] += 1
df = df.concat(selected_row)

这假设您只有一行与要搜索的rootID和parentID组合匹配。