[英]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. 使用
.loc
我可以更新相同的行,但我无法在Pandas数据框中找到任何解决方案来进行此类更新。
While i ask this question, i am try to split the Order id and search in the data frame to update the Exch values. 当我问这个问题时,我试图拆分订单ID并在数据框中搜索以更新Exch值。
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
: 或者使用
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
Another idea is get rows with P
, create Series and map
: 另一个想法是获取
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
If you would like to do that for the while dateset. 如果您想为while dateset执行此操作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.