Comparing two dataframes of different length row by row and adding columns for each row with equal value

扶醉桌前 提交于 2019-12-05 17:57:57

I recommend you to use DataFrame API which allows to operate with DF in terms of join, merge, groupby, etc. You can find my solution below:

import pandas as pd

df1 = pd.DataFrame({'Column1': [1,2,3,4,5], 
    'Column2': ['a','b','c','d','e'], 
    'Column3': ['r','u','k','j','f']})

df2 = pd.DataFrame({'Column1': [1,1,1,2,2,3,3], 'ColumnB': ['a','d','e','r','w','y','h']})

dfs = pd.DataFrame({})
for name, group in df2.groupby('Column1'):
    buffer_df = pd.DataFrame({'Column1': group['Column1'][:1]})
    i = 0
    for index, value in group['ColumnB'].iteritems():
        i += 1
        string = 'Column_' + str(i)
        buffer_df[string] = value

    dfs = dfs.append(buffer_df)

result = pd.merge(df1, dfs, how='left', on='Column1')
print(result)

The result is:

   Column1 Column2 Column3 Column_0 Column_1 Column_2
0        1       a       r        a        d        e
1        2       b       u        r        w      NaN
2        3       c       k        y        h      NaN
3        4       d       j      NaN      NaN      NaN
4        5       e       f      NaN      NaN      NaN

P.s. More details:

1) for df2 I produce groups by 'Column1'. The single group is a data frame. Example below:

   Column1 ColumnB
0        1       a
1        1       d
2        1       e

2) for each group I produce data frame buffer_df:

   Column1 Column_0 Column_1 Column_2
0        1        a        d        e

3) after that I create DF dfs:

   Column1 Column_0 Column_1 Column_2
0        1        a        d        e
3        2        r        w      NaN
5        3        y        h      NaN

4) in the end I execute left join for df1 and dfs obtaining needed result.

2)* buffer_df is produced iteratively:

step0 (buffer_df = pd.DataFrame({'Column1': group['Column1'][:1]})):
            Column1
         5       3

step1 (buffer_df['Column_0'] = group['ColumnB'][5]):      
            Column1 Column_0
         5       3       y

step2 (buffer_df['Column_1'] = group['ColumnB'][5]):      
            Column1 Column_0 Column_1
         5       3       y       h
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!