[英]Arithmetic operations on row level in pandas dataframe
I have a dataframe as below:我有一个如下的数据框:
df:
Heir_1 Heir_2 Amount_1 Amount_2
0 New Argentina 251823845.90 225432949.80
1 New Venice 219982836.00 183705325.60
2 New Denmark 419848669.41 546624742.50
3 New Russia 218120340.46 151480060.80
4 New Global 4706066755.41 4432657926.66
The concept here is Global will always be sum of Argentina
, Venice
and Others
.这里的概念是 Global 永远是
Argentina
、 Venice
和Others
总和。 But Others
row will never be mentioned.但
Others
行永远不会被提及。 I want to maintain the same structure of dataframe since it has to go through further code.我想保持数据帧的相同结构,因为它必须经过进一步的代码。
So how can i create a separate row of Others in the table by using the formula : Others = Global - Argentina - Venice
那么如何使用以下公式在表中创建单独的其他行:
Others = Global - Argentina - Venice
Expected Dataframe:预期数据帧:
df:
Heir_1 Heir_2 Amount_1 Amount_2
0 New Argentina 251823845.90 225432949.80
1 New Venice 219982836.00 183705325.60
2 New Denmark 419848669.41 546624742.50
3 New Russia 218120340.46 151480060.80
4 New Global 4706066755.41 4432657926.66
5 New Others 4234260073.51 4023519651.25
Also there is one issue, it is not necessary that all those 3 rows will be present in all scenarios.还有一个问题,没有必要在所有场景中都存在所有这 3 行。 There might be a day where either
Argentina
is absent, or Venice
is absent or Global
is absent.可能有一天
Argentina
缺席, Venice
缺席或Global
缺席。
There are 3^3 possibilities of scenarios in this case.在这种情况下,场景有 3^3 种可能性。 I can use if statements in this case but not sure if that would be a good way considering all the coding
我可以在这种情况下使用 if 语句,但不确定考虑所有编码是否是一个好方法
Try with this试试这个
if df[df['Heir_2']=='Global'].shape[0]:
df_special = df[df['animal'].isin(['Argentina','Venecia'])].sum()
amount_1 = df[df['Heir_2']=='Global']['Amount_1'] - df_special['Amount_1']
amount_2 = df[df['Heir_2']=='Global']['Amount_2'] - df_special['Amount_2']
df.append({'Heir_1':'New','Heir_2':'Others','Amount_1':amount_1,'Amount_2':amount_2},ignore_index=True)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.