有什么方法可以直接将 Series 连接到 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
最佳答案
我猜 http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html可能有帮助。
例如内部/外部连接。
pd.concat((df,s), axis=1)
Out[26]:
a b 0
0 0 100 100
1 1 101 101
2 2 102 102
3 3 103 NaN
In [27]: pd.concat((df,s), axis=1, join='inner')
Out[27]:
a b 0
0 0 100 100
1 1 101 101
2 2 102 102
关于python - 如何将系列加入数据框?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32335569/