[英]In Pandas how to update column value in one row based on another column value in another row
我想根據不同行中另一個單元格中的值更新單元格中的值。
我的數據框如下:
OrderId OrderType Exch
P_001 P NYSE
P_001_1 C | |
P_002 P |CHIX|
P_002_1 C | |
P_002_2 C | |
我希望結果如此
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|
使用.loc
我可以更新相同的行,但我無法在Pandas數據框中找到任何解決方案來進行此類更新。
當我問這個問題時,我試圖拆分訂單ID並在數據框中搜索以更新Exch值。
如果不存在值,則使用向前填充缺失值:
df['Exch'] = df['Exch'].ffill()
或者使用Series.str.split
作為新的DataFrame
,使用GroupBy.transform
和GroupBy.first
第一和第二列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
另一個想法是獲取P
行,創建系列和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
如果您想為while dateset執行此操作。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.