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

Pandas: Add Series to DataFrame ordered by column

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

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

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

  1. index 设置为 dfseries 的城市名称
  2. 通过pandasmerge
  3. 合并

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

您可以使用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

基于@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]]