【问题标题】:Create/alter a dataframe based on another dataframe column [closed]基于另一个数据框列创建/更改数据框 [关闭]
【发布时间】:2021-06-30 18:09:28
【问题描述】:

我有如下两个数据框

Inp1

Col1  col2
10     usd,hkg
20     tst, fds
30     hgf, usd

Inp2

X_col1  x_col2
200      usd
100      hkg
250      tst
280      fds

....等等

我想使用 Inp1 中的 col2 循环我的 Inp2 数据帧以实现以下输出

Out
Col1  tot  col2
10    300  usd,hkg
20    530  tst,fds

等等。 请帮助如何实现这一目标

【问题讨论】:

  • 请从intro tour 重复on topichow to ask。 “告诉我如何解决这个编码问题”不是堆栈溢出问题。我们希望您做出诚实的尝试,然后然后就您的算法或技术提出一个具体的问题。 Stack Overflow 并不打算取代现有的文档和教程。您似乎有 join、groupby 和 sum 的组合。所有这些都包含在 PANDAS 教程中,因此我们希望看到您的代码。

标签: python pandas dataframe lookup


【解决方案1】:

分裂df1['col2']然后爆炸。这使我们能够生成唯一的合并键。

>>> df1['col2'] = df1['col2'].str.split(r',\s*')
>>> df1

   Col1        col2
0    10  [usd, hkg]
1    20  [tst, fds]
2    30  [hgf, usd]

>>> df1.explode('col2')

   Col1 col2
0    10  usd
0    10  hkg
1    20  tst
1    20  fds
2    30  hgf
2    30  usd

合并后,就可以得到第二个输入框中的数量了。

>>> m = df1.explode('col2').merge(df2, left_on='col2', right_on='x_col2', how='left')
>>> m

   Col1 col2  X_col1 x_col2
0    10  usd   200.0    usd
1    10  hkg   100.0    hkg
2    20  tst   250.0    tst
3    20  fds   280.0    fds
4    30  hgf     NaN    NaN
5    30  usd   200.0    usd

将它们分配给m,然后设置要附加到Col1 索引上的新数据框df1_m 的数据(假设Col1 值是唯一的)。然后对这些值求和。我不知道为什么您想要的输入不包含匹配对之一,但如果您不想要它,您可以通过删除df['Col1'] == 30 来丢弃它。

>>> df1_m = df1.set_index('Col1')
>>> df1_m['sum'] = m.groupby('Col1')['X_col1'].sum()
>>> df1_m.reset_index()

   Col1        col2    sum
0    10  [usd, hkg]  300.0
1    20  [tst, fds]  530.0
2    30  [hgf, usd]  200.0

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-02
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-05
    • 1970-01-01
    相关资源
    最近更新 更多