【问题标题】:Pandas: Add Series to DataFrame ordered by columnPandas:将系列添加到按列排序的 DataFrame
【发布时间】:2017-01-21 04:31:12
【问题描述】:

我确定以前有人问过这个问题,但我找不到。我想将一个系列作为新列添加到 DataFrame。所有 Series 索引名称都包含在 DataFrame 的一列中,但 Dataframe 的行数比 Series 多。

DataFrame:
0 London 231
1 Beijing 328
12 New York 920
3 Singapore 1003

Series:
London AB
New York AC
Singapore B

结果应该是这样的

0 London 231 AB
1 Beijing 328 NaN
12 New York 920 AC
3 Singapore 1003 B

如何在没有循环的情况下做到这一点?谢谢!

【问题讨论】:

  • 您正在寻找合并:df.merge(pd.DataFrame('name of series'), on = 'city', how='left')
  • DataFrame 中列的名称是什么?

标签: python pandas dataframe merge series


【解决方案1】:

您可以使用pandas.DataFrame.merge()

df = pd.DataFrame({'A': [0,1,12,3], 'B': ['London', 'Beijing', 'New York', 'Singapore'], 'C': [231, 328, 920, 1003] })
    A          B     C
0   0     London   231
1   1    Beijing   328
2  12   New York   920
3   3  Singapore  1003

s = pd.Series(['AB', 'AC', 'B'], index=['London', 'New York', 'Singapore'])
London       AB
New York     AC
Singapore     B
dtype: object

df2 = pd.DataFrame({'D': s.index, 'E': s.values })
           D   E
0     London  AB
1   New York  AC
2  Singapore   B

然后,可以合并两个数据框:

merged = df.merge(df2, how='left', left_on='B', right_on='D')
    A          B     C          D    E
0   0     London   231     London   AB
1   1    Beijing   328        NaN  NaN
2  12   New York   920   New York   AC
3   3  Singapore  1003  Singapore    B

您可以删除列D

merged = merged.drop('D', axis=1)
    A          B     C    E
0   0     London   231   AB
1   1    Beijing   328  NaN
2  12   New York   920   AC
3   3  Singapore  1003    B

【讨论】:

    【解决方案2】:
    1. index 设置为dfseries 的城市名称
    2. 通过pandas组合merge

    import pandas as pd
    
    cities = ['London', 'Beijing', 'New York', 'Singapore']
    
    df_data = {
        'col_1': [0,1,12,3],
        'col_2': [231, 328, 920, 1003],
    }
    
    df = pd.DataFrame(df_data, index=cities)
    
    cities2 = ['London','New York','Singapore']
    
    series = pd.Series(['AB', 'AC', 'B'], index=cities2)
    
    
    combined = pd.merge(
        left=df,
        right=pd.DataFrame(series),
        how='left',
        left_index=True,
        right_index=True
    )
    
    print combined
    

    输出:

               col_1  col_2    0
    London         0    231   AB
    Beijing        1    328  NaN
    New York      12    920   AC
    Singapore      3   1003    B
    

    【讨论】:

      【解决方案3】:

      基于@Joe R 解决方案,并进行了一些修改。比如说,df 是你的 DataFrame,s 是你的 Series

      s = s.to_frame().reset_index()
      df = df.merge(s,how='left',left_on=df['B'],right_on=s['index']).ix[:,[0,1,3]]
      

      【讨论】:

        猜你喜欢
        • 2020-03-04
        • 1970-01-01
        • 1970-01-01
        • 2018-02-14
        • 1970-01-01
        • 2017-06-04
        • 1970-01-01
        • 2020-12-28
        • 1970-01-01
        相关资源
        最近更新 更多