【问题标题】:Pandas: Update Multiple Dataframe Columns Using Duplicate Rows From Another DataframePandas:使用来自另一个数据帧的重复行更新多个数据帧列
【发布时间】:2016-07-05 18:45:59
【问题描述】:

我有两个数据框:df1df2如果来自df2Display Namedf1Display Name 列中,我想分配df1s TypeFormatBehavior、@987654333 @ 值到 df2s 值。

我已经尝试了merge 我能想到的所有方法。我认为loc 是我最大的希望,但我似乎无法正确获取赋值语法。另外,我正在寻找一个简洁的答案 - 最好是单行。

类似这样的:

df2.loc[df2['Display Name'].isin(df1['Display Name']), /
        ['Type', 'Format', 'Behavior', 'Datatype']] = ???

我的代码:

import pandas as pd
import numpy as np

df1 = pd.DataFrame(
  {'Behavior': ['Attribute', 'Attribute', 'Attribute', 'Attribute', 'Attribute',
              'Attribute', 'Attribute', 'Metric', 'Metric', 'Metric', 'Metric',
              'Metric', 'Metric', 'Metric', 'Metric'],
   'Datatype': ['object', 'object', 'object', 'object', 'object', 'object',
              'object', 'int64', 'int64', 'int64', 'int64', 'float64',
              'float64', 'float64', 'float64'],
   'Display Name': ['Campaign', 'Campaign ID', 'Campaign ID', 'Campaign state',
                  'Campaign state', 'Currency', 'Currency', 'Impressions',
                  'Impressions', 'Clicks', 'Clicks', 'CTR', 'CTR', 'Avg. CPC',
                  'Avg. CPC'],
   'Format': ['{}', '{}', '{}', '{}', '{}', '{}', '{}', '{:,.0f}', '{:,.0f}',
            '{:,.0f}', '{:,.0f}', '{:.2f}%', '{:.2f}%', '${:,.2f}', '${:,.2f}'],
   'Type': ['String', 'String', 'String', 'String', 'String', 'String', 'String',
          'Integer', 'Integer', 'Integer', 'Integer', 'Percent', 'Percent',
          'Currency', 'Currency']},
  columns=['Display Name', 'Type', 'Format', 'Behavior', 'Datatype'])

df2 = pd.DataFrame(
  { 'Behavior': [ 'Attribute', 'Metric', 'Metric', 'Metric', 'Attribute',
                'Metric', 'Metric', 'Attribute', 'Metric', 'Metric', 'Metric'],
  'Datatype': [ 'object', 'float64', 'float64', 'float64', 'object', 'int64',
                'int64', 'object', 'float64', 'float64', 'float64'],
  'Display Name': [ 'Match type', 'Destination URL', 'Final URL',
                    'Mobile final URL', 'Labels', 'Impressions', 'Clicks',
                    'CTR', 'Avg. CPC', 'Cost', 'Avg. position'],
  'Format': [ '{}', '{:.2f}', '{:.2f}', '{:.2f}', '{}', '{:,.0f}', '{:,.0f}',
              '{}', '{:.2f}', '{:.2f}', '{:.2f}'],
  'Type': [ 'String', 'Float', 'Float', 'Float', 'String', 'Integer',
            'Integer', 'String', 'Float', 'Float', 'Float']},
  columns=['Display Name', 'Type', 'Format', 'Behavior', 'Datatype'])

df2_vals_in_df1 = df2.loc[df2['Display Name'].isin(df1['Display Name']), df2.columns[:]]
df1_vals_in_df2 = df1.loc[df1['Display Name'].isin(df2['Display Name']), df1.columns[:]]

它的样子:

>>> df1
      Display Name      Type    Format   Behavior Datatype
0         Campaign    String        {}  Attribute   object
1      Campaign ID    String        {}  Attribute   object
2      Campaign ID    String        {}  Attribute   object
3   Campaign state    String        {}  Attribute   object
4   Campaign state    String        {}  Attribute   object
5         Currency    String        {}  Attribute   object
6         Currency    String        {}  Attribute   object
7      Impressions   Integer   {:,.0f}     Metric    int64
8      Impressions   Integer   {:,.0f}     Metric    int64
9           Clicks   Integer   {:,.0f}     Metric    int64
10          Clicks   Integer   {:,.0f}     Metric    int64
11             CTR   Percent   {:.2f}%     Metric  float64
12             CTR   Percent   {:.2f}%     Metric  float64
13        Avg. CPC  Currency  ${:,.2f}     Metric  float64
14        Avg. CPC  Currency  ${:,.2f}     Metric  float64

>>> df2
        Display Name     Type   Format   Behavior Datatype
0         Match type   String       {}  Attribute   object
1    Destination URL    Float   {:.2f}     Metric  float64
2          Final URL    Float   {:.2f}     Metric  float64
3   Mobile final URL    Float   {:.2f}     Metric  float64
4             Labels   String       {}  Attribute   object
5        Impressions  Integer  {:,.0f}     Metric    int64
6             Clicks  Integer  {:,.0f}     Metric    int64
7                CTR   String       {}  Attribute   object
8           Avg. CPC    Float   {:.2f}     Metric  float64
9               Cost    Float   {:.2f}     Metric  float64
10     Avg. position    Float   {:.2f}     Metric  float64

>>> df2_vals_in_df1
  Display Name     Type   Format   Behavior Datatype
5  Impressions  Integer  {:,.0f}     Metric    int64
6       Clicks  Integer  {:,.0f}     Metric    int64
7          CTR   String       {}  Attribute   object
8     Avg. CPC    Float   {:.2f}     Metric  float64

>>> df1_vals_in_df2
   Display Name      Type    Format Behavior Datatype
7   Impressions   Integer   {:,.0f}   Metric    int64
8   Impressions   Integer   {:,.0f}   Metric    int64
9        Clicks   Integer   {:,.0f}   Metric    int64
10       Clicks   Integer   {:,.0f}   Metric    int64
11          CTR   Percent   {:.2f}%   Metric  float64
12          CTR   Percent   {:.2f}%   Metric  float64
13     Avg. CPC  Currency  ${:,.2f}   Metric  float64
14     Avg. CPC  Currency  ${:,.2f}   Metric  float64

注意df1_vals_in_df2 Display Name 可能多次使用相同的名称。它们的TypeFormatBehaviorDatatype 值在两行中始终是相同的值。

df2的预期输出

>>> df2
        Display Name     Type   Format   Behavior Datatype
0         Match type   String       {}  Attribute   object
1    Destination URL    Float   {:.2f}     Metric  float64
2          Final URL    Float   {:.2f}     Metric  float64
3   Mobile final URL    Float   {:.2f}     Metric  float64
4             Labels   String       {}  Attribute   object
5        Impressions  Integer  {:,.0f}     Metric    int64 <-- same
6             Clicks  Integer  {:,.0f}     Metric    int64 <-- same
7                CTR  Percent  {:.2f}%     Metric  float64 <-- changed
8           Avg. CPC Currency ${:,.2f}     Metric  float64 <-- changed
9               Cost    Float   {:.2f}     Metric  float64
10     Avg. position    Float   {:.2f}     Metric  float64

要点#1:第 5 行和第 6 行是相同的,因为它们在 df1df2 中是相同的。

要点 #2:第 7 行,从 String, {}, Attribute, object 更改为 Percent, {:.2f}%, Metric, float64 - 来自 df1 的行值,因为来自 df2Display Name 在 @ 中的 Display Name 中找到987654356@.

要点 #3:第 8 行,更改原因与要点 #2 中所述相同。

试过了:

Q1:Python Pandas: Merge or Filter DataFrame by Another. Is there a Better Way?

没有解决这个问题,因为我不想创建一个新的数据框;我正在尝试从另一个数据框中替换现有数据框中的值。

Q2:Replace column values based on another dataframe python pandas - better way?

没有解决这个问题,因为该示例包含一个具有正确值的 df,而我的情况是一个具有正确和不正确值的 df。

抱歉,这是一个很长的问题。我只是想提供足够的上下文。

【问题讨论】:

  • 好吧,你可以通过大幅缩小 df1 和 df2 来使这更容易阅读。 5 行和 2 列可以很容易地理解这一点。说了这么多,你是在找combine_first()吗?
  • 感谢您的反馈。可能是 TMI(信息太多)。我确实找到了您的建议 combine_first() 的解决方案,我将发布。但是,我不喜欢它,因为它附加了需要重复数据删除的行。其次,为了得到上面的预期输出,我需要做一个神奇的自定义映射(一定是一个更简单的方法)。

标签: python pandas merge lookup


【解决方案1】:

我认为 combine_first 将是一个优雅的解决方案,根据 JohnE,只要您将 Display Name 设置为索引。这让我想到了另一点。我认为只有当“显示名称”对应于每个表中的一组属性时,您的任务才定义明确。假设您可以删除重复项、设置索引并使用.update,如下所示:

df1 = df1.drop_duplicates()

df1 = df1.set_index('Display Name')
df2 = df2.set_index('Display Name')

df2_c = df2.copy()

df2.update(df1)
df1.update(df2_c)

del df2_c

您可以根据需要使用辅助索引重置df1 的尺寸。

【讨论】:

  • update() 的文档中,它说“对齐索引”。这就是您将索引设置为“显示名称”的原因吗?
  • 是的,就是这样。
  • 接受这个答案是正确的。但是,这个答案与我上面提到的 Q1 非常相似。而且,没有其他人(除了我自己)提供了答案。所以......最佳答案。
【解决方案2】:

不理想,但我能够重新创建我的预期输出。问题是,我想避免创建 df3 并希望在 df2 内进行替换,所以这并不理想。

df2 之前:

        Display Name     Type   Format   Behavior Datatype
0         Match type   String       {}  Attribute   object
1    Destination URL    Float   {:.2f}     Metric  float64
2          Final URL    Float   {:.2f}     Metric  float64
3   Mobile final URL    Float   {:.2f}     Metric  float64
4             Labels   String       {}  Attribute   object
5        Impressions  Integer  {:,.0f}     Metric    int64
6             Clicks  Integer  {:,.0f}     Metric    int64
7                CTR   String       {}  Attribute   object
8           Avg. CPC    Float   {:.2f}     Metric  float64
9               Cost    Float   {:.2f}     Metric  float64
10     Avg. position    Float   {:.2f}     Metric  float64

df3 之后:

df3 = df2.combine_first(df1).drop_duplicates('Display Name', keep='last')
df3 = df3.set_index(df3['Display Name'].map(dict(zip(df2['Display Name'], df2.index)))).sort_index().reset_index(drop=True)

        Display Name      Type    Format   Behavior Datatype
0         Match type    String        {}  Attribute   object
1    Destination URL     Float    {:.2f}     Metric  float64
2          Final URL     Float    {:.2f}     Metric  float64
3   Mobile final URL     Float    {:.2f}     Metric  float64
4             Labels    String        {}  Attribute   object
5        Impressions   Integer   {:,.0f}     Metric    int64
6             Clicks   Integer   {:,.0f}     Metric    int64
7                CTR   Percent   {:.2f}%     Metric  float64
8           Avg. CPC  Currency  ${:,.2f}     Metric  float64
9               Cost     Float    {:.2f}     Metric  float64
10     Avg. position     Float    {:.2f}     Metric  float64

df2前后对比:

   Display Name   Type Format Behavior Datatype
0          True   True   True     True     True
1          True   True   True     True     True
2          True   True   True     True     True
3          True   True   True     True     True
4          True   True   True     True     True
5          True   True   True     True     True
6          True   True   True     True     True
7          True  False  False    False    False
8          True  False  False     True     True
9          True   True   True     True     True
10         True   True   True     True     True

【讨论】:

    猜你喜欢
    • 2019-07-10
    • 1970-01-01
    • 2015-12-31
    • 2021-06-19
    • 2020-09-20
    • 2022-10-14
    • 1970-01-01
    • 2018-12-25
    • 2016-12-20
    相关资源
    最近更新 更多