【问题标题】:Pandas, combining information from 2 dataframes and one dictionaryPandas,结合来自 2 个数据框和一个字典的信息
【发布时间】:2017-08-01 12:44:27
【问题描述】:

嗯,这有点难以解释......

假设您有 2 个 pandas 数据框和 1 个字典。

df1 = pd.DataFrame(np.random.randn(5, 3), columns=['b', 'c','d'])
df1['a'] = pd.Series(['1 A1-1','3 A1-1','8 A1-2','17 A1-3','45 A1-16'], index=df1.index)
df1 = df1.reindex_axis(sorted(df1.columns), axis=1)


df2 = pd.DataFrame([['1 A1-1',5],['2 A1-1',8],['3 A1-1',10],['8 A1-2',4],['17 A1-3',1],['45 A1-16',2]], columns = ['m','n'])

dt = {'A1-1':100, 'A1-2':150, 'A1-3':200, 'A1-4':250, 'A1-5':300, 'A1-16':950}

df1['a']df2['m'] 包含 IDs,有些是相同的。 df2['n'] 包含附加值。 dt 包含 ID 组的基本值,例如 A1-1A1-2 等。

我现在想比较/合并df1df2dt 中的数据,以便能够向df1 添加一个新列: 每当df1['a']df2['m'] 中的IDs 相同时,将字典中具有相同字符串部分的基本值添加到相应的df2['n'] 中,然后将结果转移到df1['e'] 中的新列中。

我遇到的一个主要问题是 ID 和 dict 键中的字符串处理:例如 df1 中的 '1 A1-1'df2dt 中的 'A1-1' - 不知道如何比较它们。

最有帮助的是df1['e'] = pd.Series([105,110,154,201,952], index = df1.index)这样的结果。

感谢您的帮助。

【问题讨论】:

    标签: python pandas dictionary dataframe string-comparison


    【解决方案1】:

    在我看来,这是一个很好解释的问题。

    首先split 由空白列a 选择第二个列表str[1] 然后map 通过dict 并添加maped 列a 通过Series 创建由set_index

    df1['e'] = df1['a'].str.split().str[1].map(dt) + df1['a'].map(df2.set_index('m')['n'])
    print (df1)
              a         b         c         d    e
    0    1 A1-1  0.026375  0.260322 -0.395146  105
    1    3 A1-1 -0.204301 -1.271633 -2.596879  110
    2    8 A1-2  0.289681 -0.873305  0.394073  154
    3   17 A1-3  0.935106 -0.015685  0.259596  201
    4  45 A1-16 -1.473314  0.801927 -1.750752  952
    

    编辑:

    map 函数使用 dict 的键替换某些列中的值。按系列的相似映射,仅使用 instaed 键 index 值,而不是 values 使用值。

    #sample data
    df = pd.DataFrame({'a':['bar','foo', 'baz'], 'b':[7,8,9]})
    print (df)
         a  b
    0  bar  7
    1  foo  8
    2  baz  9
    
    #dict and df for mapping
    d = {'foo':15, 'bar':20}
    df2 = pd.DataFrame({'m':['baz','bar','foo'], 'n':[3,4,5]})
    print (df2)
         m  n
    0  baz  3
    1  bar  4
    2  foo  5
    
    #create Series for map
    print (df2.set_index('m')['n'])
    m
    baz    3
    bar    4
    foo    5
    Name: n, dtype: int64
    
    df['c'] = df['a'].map(d)
    df['d'] = df['a'].map(df2.set_index('m')['n'])
    print (df)
         a  b     c  d
    0  bar  7  20.0  4
    1  foo  8  15.0  5
    2  baz  9   NaN  3
    

    【讨论】:

    • 非常好!非常感谢。虽然,在那种情况下,我并不完全掌握地图的功能。请您给我一个简短的解释。
    猜你喜欢
    • 2023-04-08
    • 2018-05-04
    • 1970-01-01
    • 2015-05-30
    • 2022-09-28
    • 2017-10-20
    • 1970-01-01
    • 2019-03-31
    相关资源
    最近更新 更多