I have a pandas dataframe df1 as shown below: It shows exports volume from A to B, B to A and A to C in three rows. Trade is possible in both directions. enter image description here

df1.to_dict()份退货

{‘Country1’:{0:‘a’,1:‘B’,2:‘a’},‘Country2’:{0:‘B’,1:‘a’, 2:‘C’},‘Value’:{0:3,1:5,2:3}}

I want a second dataframe df2 based on df1 which shows the net trade volume between countries. For example, A to C has a net trade volume of 3 units, and B to A has a net trade volume of 2 units (5-3). This needs to be reflected in the second dataframe as shown below: enter image description here

如何在df1的基础上自动创建df2? 我有大量的国家/地区,所以我想让这个过程自动化.

推荐答案

您可以交换名称、merge和Filter:

val = (df[['Country1', 'Country2']]
 .merge(df.rename(columns={'Country1': 'Country2',
                           'Country2': 'Country1'}),
        how='left')['Value']
 .rsub(df['Value'], fill_value=0)
)

out = (df.assign(**{'Net Value': val})
         .query('`Net Value` >= 0')
         .drop(columns='Value')
      )

输出:

  Country1 Country2  Net Value
1        B        A        2.0
2        A        C        3.0

Python相关问答推荐

在pandas DataFrame上运行apply()时如何访问DateTime索引?

X射线扫描显示Docker中的pip漏洞,尽管图像中未安装pip

ValueRight:参数目标和输出必须具有相同的形状.接收:目标.形状=(无,512),输出.形状=(无,3)

如何计算部分聚合数据的统计数据

当测试字符串100%包含查询字符串时,为什么t fuzzywuzzy s Process.extractBests不给出100%分数?

按 struct 值对Polars列表[struct[]]排序

如何在超时的情况下同步运行Matplolib服务器端?该过程随机挂起

阅读Polars Python中管道的函数定义

使用scipy. optimate.least_squares()用可变数量的参数匹配两条曲线

如何在Deliveryter笔记本中从同步上下文正确地安排和等待Delivercio代码中的结果?

对某些列的总数进行民意调查,但不单独列出每列

Python键入协议默认值

如何使用表达式将字符串解压缩到Polars DataFrame中的多个列中?

将9个3x3矩阵按特定顺序排列成9x9矩阵

Python—从np.array中 Select 复杂的列子集

如何使用scipy的curve_fit与约束,其中拟合的曲线总是在观测值之下?

UNIQUE约束失败:customuser. username

考虑到同一天和前2天的前2个数值,如何估算电力时间序列数据中的缺失值?

在matplotlib中使用不同大小的标记顶部添加批注

用SymPy在Python中求解指数函数