Pandas:将系列添加到按列排序的DataFrame

时间:2016-09-13 14:16:08

标签: python pandas dataframe merge series

我确信之前有人问过,但我找不到了。我想将一个Series添加为DataFrame的新列。所有Seri​​es Index名称都包含在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

如何在没有循环的情况下执行此操作?谢谢!

3 个答案:

答案 0 :(得分:0)

  1. index设置为dfseries
  2. 的城市名称
  3. 通过pandas merge
  4. 进行组合
    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
    

答案 1 :(得分:0)

您可以使用Conditional comments are no longer supported after IE10

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 :(得分:0)

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

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