【问题标题】:Create a new column based on other columns as indices for another dataframe基于其他列创建一个新列作为另一个数据框的索引
【发布时间】:2017-08-15 20:49:15
【问题描述】:

假设我有一个数据框,其中至少有两列 col1 和 col2。此外,我还有另一个数据框,其列名是 col 1 中的值,其索引是 col2 中的值。

import pandas as pd
df1 = pd.DataFrame( {'col1': ['x1', 'x2', 'x2'], 'col2': ['y0', 'y1', 'y0']})
print(df1)
  col1 col2
0   x1   y0
1   x2   y1
2   x2   y0

print(df2)
     y0   y1
x1    1    4
x2    2    5
x3    3    6

现在我想添加 col3,它可以在 col1 的索引和 col2 的列中为我提供第二个数据帧的值。 结果应如下所示:

   col1  col2  col3
0    x1    y0     1
1    x2    y1     5
2    x2    y0     2

谢谢大家!

【问题讨论】:

    标签: python pandas dataframe


    【解决方案1】:

    您可以将stack 用于新的dfmerge

    df2 = df2.stack().reset_index()
    df2.columns = ['col1','col2','col3']
    print (df2)
      col1 col2  col3
    0   x1   y0     1
    1   x1   y1     4
    2   x2   y0     2
    3   x2   y1     5
    4   x3   y0     3
    5   x3   y1     6
    
    print (pd.merge(df1, df2, on=['col1','col2'], how='left'))
      col1 col2  col3
    0   x1   y0     1
    1   x2   y1     5
    2   x2   y0     2
    

    另一种解决方案是使用join 创建新的Series

    s = df2.stack().rename('col3')
    print (s)
      col1 col2
    0   x1   y0
    1   x2   y1
    2   x2   y0
    x1  y0    1
        y1    4
    x2  y0    2
        y1    5
    x3  y0    3
        y1    6
    Name: col3, dtype: int64
    
    print (df1.join(s, on=['col1','col2']))
      col1 col2  col3
    0   x1   y0     1
    1   x2   y1     5
    2   x2   y0     2
    

    【讨论】:

    • 第二个的优雅。
    • @NickilMaveli - 谢谢。
    【解决方案2】:

    简单连接

    Pandas 支持索引和列的连接操作,这意味着你可以这样做:

    df1.merge(df2, left_on='col1', right_index=True)
    

    生产

      col1 col2  y0  y1
    0   x1   y0   1   4
    1   x2   y1   2   5
    2   x2   y0   2   5
    

    将正确的值放入col3 是下一步

    申请

    这有点效率低下,但它是一种将正确数据放入一列的方法

    df['col3'] = df[['col2', 'y0', 'y1']].apply(lambda x: x[int(x[0][1]) + 1], axis=1)
    

    【讨论】:

      猜你喜欢
      • 2020-10-11
      • 2018-02-14
      • 1970-01-01
      • 2016-05-07
      • 2023-03-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-07-18
      相关资源
      最近更新 更多