简体   繁体   中英

find first column elements in entire data frame and return first column values in front of each row(Pandas)

I have below source data frame and need to match each element in first column(A) with columns B to E and if they are found, return cell value in first column and matched row in a new Column(F)[in front of related element in column(A), separated by commas. for instance, 'a' in Column A is repeated 4 times in columns B to E and related values in column(A)['b','c','d','e'] are returned in new column(F). I do this by for loop in VBA excel but it is tricky for me to convert it to python. appreciate your support.

Source Data Frame:

A   B   C   D   E

a   -            
b   a            
c   a            
d   b   a   -    
e   d   b   a   -

desired Data Frame:

A   B   C   D   E   F   

a   -               b,c,d,e
b   a               d,e
c   a               
d   b   a   -       e
e   d   b   a   -   

below is the codes I have written so far but last line return a series in column(F)

import pandas as pd
import numpy as np
df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'},
 'B': {0: '-', 1: 'a', 2: 'a', 3: 'b', 4: 'd'}})

df['C'] = np.where(df['B'].isin(df['A'].values), df['B'], np.nan)
df['C'] = df['C'].map(dict(zip(df.A.values, df.B.values)))
df['D'] = np.where(df['C'].isin(df['B'].values), df['C'], np.nan)
df['D'] = df['D'].map(dict(zip(df.B.values, df['C'].values)))
df['E'] = np.where(df['D'].isin(df['C'].values), df['D'], np.nan)
df['E'] = df['E'].map(dict(zip(df['C'].values, df['D'].values)))
df1=df.iloc[:,1:5]
df['F']=[np.where(df1.values == x) for x in df['A']]

I've never worked with pandas. I'd like to see other solutions with np aswell.

import pandas as pd
import numpy as np
from IPython.display import display
df = pd.DataFrame({'A': {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e'},
 'B': {0: '-', 1: 'a', 2: 'a', 3: 'b', 4: 'd'}})

df['C'] = np.where(df['B'].isin(df['A'].values), df['B'], np.nan)
df['C'] = df['C'].map(dict(zip(df.A.values, df.B.values)))
df['D'] = np.where(df['C'].isin(df['B'].values), df['C'], np.nan)
df['D'] = df['D'].map(dict(zip(df.B.values, df['C'].values)))
df['E'] = np.where(df['D'].isin(df['C'].values), df['D'], np.nan)
df['E'] = df['E'].map(dict(zip(df['C'].values, df['D'].values)))
df1=df.iloc[:,1:5]

# -->
df['F']=(t:=[np.where(df1.values == x) for x in df['A']])

f = []
my_data= df.to_dict()
for row in [vals[0].tolist() for vals in t]:
 temp = []
 for x in row:
  temp.append(my_data["A"][x])
 f.append(",".join(temp))
df['F'] = f
display(df)

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