[英]Pandas: Add Series to DataFrame ordered by column
我敢肯定這是以前問過的,但我找不到。 我想將Series作為新列添加到DataFrame。 所有系列索引名稱都包含在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
和series
城市名稱都設置為index
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
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]]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.