pandas 如何将系列加入数据帧?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32335569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:50:43  来源:igfitidea点击:

How to join a Series to a DataFrame?

pythonjoinpandasdataframe

提问by Pythonista anonymous

Is there any way to join a Series to a DataFrame directly?

有没有办法将系列直接加入数据帧?

The join would be on a field of the dataframe and on the index of the series.

连接将在数据帧的字段和系列的索引上。

The only way I found was to convert the series to a dataframe first, as in the code below.

我发现的唯一方法是首先将系列转换为数据帧,如下面的代码所示。

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

回答by Alex

I guess http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.htmlmight help.

我想http://pandas.pydata.org/pandas-docs/stable/generated/pandas.concat.html可能会有所帮助。

For example inner/outer join.

例如内/外连接。

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

回答by Ando Jurai

That's a very late answer, but what worked for me was building a dataframe with the columns you want to retrieve in your series, name this series as the index you need, append the series to the dataframe (if you have supplementary elements in the series they are added to the dataframe, which in some application may be convenient), then join the final dataframe by this index to the original dataframe you want to expand. Agreed it is not direct, but that's still the most convenient way if you have a lot of series, instead of transforming each in a dataframe first.

这是一个很晚的答案,但对我有用的是构建一个包含您要在系列中检索的列的数据框,将该系列命名为您需要的索引,将该系列附加到该数据框中(如果您在该系列中有补充元素它们被添加到数据帧中,这在某些应用程序中可能很方便),然后通过此索引将最终数据帧连接到您要扩展的原始数据帧。同意它不是直接的,但是如果您有很多系列,这仍然是最方便的方法,而不是首先在数据框中转换每个系列。

回答by Alex

Try concat():

尝试连接():

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))

new_df = pd.concat((df, s), axis=1)
print new_df

This prints:

这打印:

   a    b    0
0  0  100  100
1  1  101  101
2  2  102  102
3  3  103  NaN