简体   繁体   中英

In Pandas how to update column value in one row based on another column value in another row

I want to update value in a cell based on value in another cell in different row.

My dataframe is given below:

OrderId   OrderType   Exch
    P_001       P         NYSE
    P_001_1     C          | | 
    P_002       P          |CHIX|
    P_002_1     C          | |
    P_002_2     C          | |

And i want the result to be

OrderId   OrderType    Exch

P_001       P          |NYSE|
P_001_1     C          |NYSE|
P_002       P          |CHIX|
P_002_1     C          |CHIX|
P_002_2     C          |CHIX|

Using .loc i can update same rows but i am not able to find any solution in Pandas data-frame for such an update.

While i ask this question, i am try to split the Order id and search in the data frame to update the Exch values.

If not exist values are missing, use forward filling missing values:

df['Exch'] = df['Exch'].ffill()

Or use Series.str.split for new DataFrame , groupby by first and second column with GroupBy.transform and GroupBy.first :

df1 = df['OrderId'].str.split('_', expand=True)
df['Exch'] = df.groupby([df1[0], df1[1]])['Exch'].transform('first')

print (df)
   OrderId OrderType  Exch
0    P_001         P  NYSE
1  P_001_1         C  NYSE
2    P_002         P  CHIX
3  P_002_1         C  CHIX
4  P_002_2         C  CHIX

Another idea is get rows with P , create Series and map :

s = df[df['OrderType'].eq('P')].set_index('OrderId')['Exch']
df['Exch'] = df['OrderId'].str.rsplit('_', n=1).str[0].map(s).fillna(df['Exch'])
print (df)
   OrderId OrderType  Exch
0    P_001         P  NYSE
1  P_001_1         C  NYSE
2    P_002         P  CHIX
3  P_002_1         C  CHIX
4  P_002_2         C  CHIX
df= df.ffill(axis = 0) 
print(df)

         a  b     c
0    P_001  P  NYSE
1  P_001_1  C  None
2    P_002  P  CHIX
3  P_002_1  C  None
4  P_002_2  C  None
         a  b     c
0    P_001  P  NYSE
1  P_001_1  C  NYSE
2    P_002  P  CHIX
3  P_002_1  C  CHIX
4  P_002_2  C  CHIX

If you would like to do that for the while dateset.

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