gpt4 book ai didi

python - 来自类别列中的类标记的多个数据帧的 pairplot 列

转载 作者:行者123 更新时间:2023-12-03 16:58:59 27 4
gpt4 key购买 nike

我不确定该怎么做,但我相信这是可行的。我有三个 dataframes 具有相同的列定义但来自不同年份的数据集。然后,我想对数字列逐一绘制,并绘制来自这些 df 的数据,适本地标记数据来自的集合。目标是了解每一列的数据模式(与年份相比)。

我用这 2 个 dataframes 说明了我的意思,其中 df1 中的数据集来自 2018df22019 年开始:

df1
id speed accelaration jerk mode
0 1 1.94 -1.01 1.05 foot
1 1 0.93 0.04 -0.17 foot
2 3 0.50 -0.16 0.05 bike
3 3 0.57 0.05 0.19 bike
4 5 3.25 -0.13 -0.09 bus
5 5 0.50 -0.25 0.25 bus
6 5 0.25 0.10 0.25 bus

df2
id speed accelaration jerk mode
0 17 1.5 0.00 0.00 foot
1 17 1.5 0.00 -0.30 foot
2 17 1.5 -0.30 0.06 foot
3 15 4.55 0.01 -0.36 bike
4 15 4.57 -0.35 0.02 bike
5 87 9.82 -0.29 -0.12 bus
6 87 8.65 -0.78 0.07 bus

忽略 id 列,我想得到如下图所示的结果(这只是我绘制的预期结果的示例):

enter image description here

简单地为每个 df 调用 sns.pairplot() 两次不会给出预期的结果,就像我那样:

sns.pairplot(df1, vars=df1.columns[1:4], hue='mode')
sns.pairplot(df2, vars=df2.columns[1:4], hue='mode')
plt.show()

enter image description here

有人可以帮助描述如何从中获得预期的答案吗?

最佳答案

  • 给定数据框,为每个数据框添加一个'year'
  • 使用pandas.concat 合并数据帧
    • 重置索引,但不要删除它。该索引将用作 x 轴,因为尚未提供。这将保持每个数据帧中数据的相对位置
  • 'speed''acceleration''jerk'堆叠到一列中,'event',创建一个长而整洁的格式数据框。
  • seaborn.FacetGrid 绘制数据并映射为 seaborn.scatterplot .
    • 'index' 列,而不是 dfl.index,用作 x 轴
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt

# add year to the dataframes
df1['year'] = 2018
df2['year'] = 2019

# combine the dataframes
df = pd.concat([df1, df2]).reset_index()

# stack the dataframe into a long (tidy) format
dfl = df.set_index(['index', 'id', 'mode', 'year']).stack().reset_index().rename(columns={'level_4': 'event', 0: 'value'})

# display(dfl)
index id mode year event value
0 0 1 foot 2018 speed 1.94
1 0 1 foot 2018 accelaration -1.01
2 0 1 foot 2018 jerk 1.05
3 1 1 foot 2018 speed 0.93
4 1 1 foot 2018 accelaration 0.04
5 1 1 foot 2018 jerk -0.17
6 2 3 bike 2018 speed 0.50
7 2 3 bike 2018 accelaration -0.16
8 2 3 bike 2018 jerk 0.05
9 3 3 bike 2018 speed 0.57


# plot a FacetGrid mapped with a scatterplot
g = sns.FacetGrid(data=dfl, row='event', col='mode', hue='year')
g.map(sns.scatterplot, 'index', 'value').add_legend(bbox_to_anchor=(1, 0.5), loc='center left')
g.fig.tight_layout()

enter image description here

关于python - 来自类别列中的类标记的多个数据帧的 pairplot 列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63938320/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com