有什么办法直接将一个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中的列添加到数据框中,但是如何指定它应该是左外连接还是内连接,以及如何指定该系列的索引应该匹配哪个数据帧的列?谢谢 –