以各个城市的天气为例, 先准备下面的数据:
印度天气的相关信息:
import pandas as pdindia_weather = pd.DataFrame({ 'city': ['mumbai', 'delhi', 'banglore'], 'temperature': [32, 34, 30], 'humidity': [80, 60, 72] }) india_weather
美国天气的相关信息:
us_weather = pd.DataFrame({ 'city': ['newyork', 'chicago', 'orlando'], 'temperature': [21, 24, 32], 'humidity': [68, 65, 70] }) us_weather
用 concat 组合上面两个 dataframe:
df = pd.concat([india_weather, us_weather]) df
输出:
![](https://img2018.cnblogs.com/blog/1603147/201902/1603147-20190224230244168-434138703.jpg)
上面的输出最左边的序列号是重复的, 原因是数据分别来自两个 dataframe 的索引值, 可以通过忽略原本的索引来做改变:
df = pd.concat([india_weather, us_weather], ignore_index=True)
输出:
![](https://img2018.cnblogs.com/blog/1603147/201902/1603147-20190224230251823-733317153.jpg)
下面再介绍另一种输出形式:
df = pd.concat([india_weather, us_weather], keys=['india', 'us'])
输出:
![](https://img2018.cnblogs.com/blog/1603147/201902/1603147-20190224230259193-1581042070.jpg)
由于我们上面设置了关键字, 所以下面就可以利用这个关键字获取相关的信息:
df.loc['india']
输出:
![](https://img2018.cnblogs.com/blog/1603147/201902/1603147-20190224230306510-2068603533.jpg)
从我们一系列的输出可以看出, 这些组合都是纵向的组合, 那么在实际应用中, 我们是经常需要做横向组合的, 比如下面的例子:
temperature_df = pd.DataFrame({ 'city': ['newyork', 'chicago', 'orlando'], 'temperature': [21, 24, 32], })
windspeed_df = pd.DataFrame({ 'city': ['newyork', 'chicago', 'orlando'], 'temperature': [7, 12, 9], })
横向组合:
df = pd.concat([temperature_df, windspeed_df], axis=1)
输出:
![](https://img2018.cnblogs.com/blog/1603147/201902/1603147-20190224230314728-495995081.jpg)
windspeed_df = pd.DataFrame({ 'city': ['chicago', 'newyork'], 'temperature': [12, 7], })
我改动了关于风速的数据, 颠倒了城市的顺序, 还删掉了一个城市, 大家可以自己运行一下, 看到输出的结果有点乱了. 遇到这种情况, 我们可以通过给原数据加索引的方式, 来设置数据的排序:
temperature_df = pd.DataFrame({ 'city': ['newyork', 'chicago', 'orlando'], 'temperature': [21, 24, 32], }, index=[0, 1, 2]) windspeed_df = pd.DataFrame({ 'city': ['chicago', 'newyork'], 'temperature': [12, 7], }, index=[1, 0])
输出:
![](https://img2018.cnblogs.com/blog/1603147/201902/1603147-20190224230322792-1692168948.jpg)
下面再介绍一下 dataframe 与 series 的组合方式:
s = pd.Series(['Humidity', 'Dry', 'Rain'], name='event')df = pd.concat([temperature_df, s], axis=1)
输出:
![](https://img2018.cnblogs.com/blog/1603147/201902/1603147-20190224230329979-127386176.jpg)
以上就是关于 concat 的组合数据的一些常用方法啦, 下节课会带来更劲爆的组合方法, enjoy~~~