[Python Cookbook]Pandas: How to increase columns for DataFrame?Join/Concat

1. Combine Two Series

series1=pd.Series([1,2,3],name='s1')
series2=pd.Series([4,5,6],name='s2')
df = pd.concat([series1, series2], axis=1)

Out:

series1=pd.Series([1,2,3],index=['a','b','c'],name='s1')
series2=pd.Series([4,5,6],index=['a','b','d'],name='s2')
df = pd.concat([series1, series2], axis=1)

Out:

 Note: Two series must have names.

2. Add a series to a data frame

df=pd.DataFrame([1,2,3],index=['a','b','c'],columns=['s1'])
s2=pd.Series([4,5,6],index=['a','b','d'],name='s2')
df['s2']=s2

Out:

This method is equivalant to left join:

d2.join(s2,how='left',inplace=True)

To get the same result as Part 1, we can use outer join:

d2.join(s2,how='outer',inplace=True)

猜你喜欢

转载自www.cnblogs.com/sherrydatascience/p/12375589.html