参数pd.concat(objs, axis=0, join='outer', join_axes=None, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, copy=True)
objs 需要连接的对象,eg [df1, df2]axis axis = 0, 表示在水平方向(row)进行连接 axis = 1, 表示在垂直方向(column)进行连接join outer, 表示index全部需要; inner,表示只取index重合的部分join_axes 传入需要保留的indexignore_index 忽略需要连接的frame本身的index。当原本的index没有特别意义的时候可以使用keys 可以给每个需要连接的df一个label
import pandas as pdimport tushare as ts
横向连接,axis = 0
比如说,当我们需要某只股票1月和7月前几天的交易数据
report1 = ts.get_k_data('600036', start='2017-01-01', end='2017-01-05')report2 = ts.get_k_data('600036', start='2017-07-01', end='2017-07-05')
report1

image.png
report2

image.png
pd.concat([report1, report2], axis=0)
纵向连接,axis = 1
比如说,我们需要观察8月份某只股票与上证指数的走势对比
stock = ts.get_k_data('600036', start='2017-08-01', end='2017-08-31')sh = ts.get_k_data('sh', start='2017-08-01', end='2017-08-31')trend = pd.concat([stock, sh], axis=1)trend.head()

image.png
column name 有重复,似乎不是很好处理
trend = pd.concat([stock, sh], axis=1, keys=['zsyh', 'sh'])trend.head()

image.png
% matplotlib inline
trend.loc[:, [('zsyh', 'close'), ('sh', 'close')]].plot(kind='line', secondary_y=[('sh', 'close')])

image.png
上面使用了keys来创建了MultiIndexing,感觉还挺麻烦
现在换一种方法,来看看ignore_index的作用
trend = pd.concat([stock, sh], axis=1, ignore_index=True)trend.head()

image.png
trend.rename(columns={2: 'zsyh_close', 9: 'sh_close'}, inplace=True)trend.head()

image.png
trend.loc[:, ['zsyh_close', 'sh_close']].plot(kind='line', secondary_y=['sh_close'])

image.png
作者:减个肥怎么就那么难
链接:https://www.jianshu.com/p/421f040dfe2f
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

