简体   繁体   中英

Create new rows to pandas dataframe based on condition efficiently

I have two pandas dataframes: one with IDs and values and another that maps IDs with other IDs. The objective is to create a new dataframe that is based on df1. It loops through each sourceId in df1 and looks to df2, a mapping df, for matches in sourceId. If a match is found, a new row is created with the same value as in df1. So if multiple matches are found, the loop creates multiple rows (eg with ids A and C). If only one match is found (eg with id B), only one row is created.

The below code does exactly what I want, but it does it very slowly. In my original dataset df1 is 440K rows and df2 has mappings for thousands of different IDs - currently the code runs at 10-25 it/s which is too much.

Is there a faster way to do this that would benefit from matrix calculations/other benefits of numpy/pandas?

import pandas as pd
df1 = pd.DataFrame({
    'SourceId': ['A', 'B', 'C', 'A', 'C', 'B'], 
    'value': [1, 5, 12, 30, 32, 55], 
    'time': [pd.to_datetime('2020-04-04 08:49:52.166498900+0000'),
             pd.to_datetime('2020-08-14 06:12:40.860460500+0000'),
             pd.to_datetime('2020-05-13 09:20:50.052688900+0000'),
             pd.to_datetime('2020-03-09 13:55:17.335340600+0000'),
             pd.to_datetime('2020-08-14 09:30:56.359635400+0000'),
             pd.to_datetime('2020-01-31 23:03:46.539892900+0000')],
    'otherInfo': ['0A10a', '055jA', 'boAqz', '0t,m5A', '09tjq1', 'akk_1!']})
df2 = pd.DataFrame({'SourceId': ['A', 'A', 'B', 'C', 'C', 'C'], 'TargetId': ['A', 'Q', 'B', 'C', 'B', 'X'], 'trueIfMatch': [1, 0, 1, 1, 0, 0]})

df3 = pd.DataFrame()
for r in df1.itertuples():
    SourceId = r.SourceId
    value = r.value
    time = r.time
    otherInfo = r.otherInfo
    if SourceId in df2.SourceId.unique():
        entries = df2.loc[df2.SourceId == SourceId].TargetId.tolist()
        for entry in entries:
            df3 = df3.append({
                'sourceId': SourceId,
                'targetId': entry,
                'value': value,
                'time': time,
                'otherInfo': otherInfo
            }, ignore_index=True)
display(df3)

在此处输入图片说明 在此处输入图片说明 在此处输入图片说明

Use df.merge with sort_values :

In [2293]: df3 = df1.merge(df2, on='SourceId').sort_values('value')

In [2294]: df3
Out[2294]: 
   SourceId  value TargetId
0         A      1        A
1         A      1        Q
4         B      5        B
6         C     12        C
7         C     12        B
8         C     12        X
2         A     30        A
3         A     30        Q
9         C     32        C
10        C     32        B
11        C     32        X
5         B     55        B

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM