Pandas 基础 (8) - 用 concat 组合 dataframe

以各个城市的天气为例, 先准备下面的数据:

印度天气的相关信息:

import pandas as pd
india_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

输出:

Pandas 基础(8) - 用 concat 组合 dataframe

上面的输出最左边的序列号是重复的, 原因是数据分别来自两个 dataframe 的索引值, 可以通过忽略原本的索引来做改变:

df = pd.concat([india_weather, us_weather], ignore_index=True)

还可以这样输出:

df = pd.concat([india_weather, us_weather], keys=['india', 'us'])

输出:
Pandas 基础(8) - 用 concat 组合 dataframe

由于上面设置了关键字, 所以就可以利用这个关键字获取相关的信息:

df.loc['india']

输出:
Pandas 基础(8) - 用 concat 组合 dataframe

从上面一系列的输出可以看出, 这些组合都是纵向的组合, 那么在实际应用中, 我们是经常需要做横向组合的, 比如下面的例子:

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)

输出:
Pandas 基础(8) - 用 concat 组合 dataframe

从目前的输出来看, 两组数据对应的很好, 同一个城市都在同一行上, 那如果我们把数据源改下:

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

输出:
Pandas 基础(8) - 用 concat 组合 dataframe

这样数据顺序就调好了.

下面再介绍一下 dataframe 与 series 的组合方式:

s = pd.Series(['Humidity', 'Dry', 'Rain'], name='event')

df = pd.concat([temperature_df, s], axis=1)

输出:
Pandas 基础(8) - 用 concat 组合 dataframe

以上就是关于 concat 的组合数据的一些常用方法啦, 下一篇会带来更劲爆的组合方法, enjoy~~~

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 1

有点像sql的join

4年前 评论
Coolest 4年前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!