有什麼辦法直接將一個Series加入到DataFrame中?如何將一個系列加入DataFrame?
連接將位於數據框的字段和系列的索引上。
我發現的唯一方法是首先將該系列轉換爲數據框,如下面的代碼所示。
import numpy as np
import pandas as pd
df = pd.DataFrame()
df['a'] = np.arange(0, 4)
df['b'] = np.arange(100, 104)
s = pd.Series(data=np.arange(100, 103))
# this doesn't work
# myjoin = pd.merge(df, s, how='left', left_on='a', right_index=True)
# this does
s = s.reset_index()
# s becomes a Dataframe
# note you cannot reset the index of a series inplace
myjoin = pd.merge(df, s, how='left', left_on='a', right_on='index')
print myjoin
對不起,你只是想添加一個新的列,例如:'df ['new_col'] = df ['a']。map(s)'? – EdChum
我相信你的問題的解決方案(用'reset_index()'來製作一個數據框)是正確的解決方案。 – itzy
我想將Series中的列添加到數據框中,但是如何指定它應該是左外連接還是內連接,以及如何指定該系列的索引應該匹配哪個數據幀的列?謝謝 –