我想将数据显示为与两个数值列相对应的两个类别列的并排方框图。
这是我的尝试
# create a list of our conditions
conditions_BPXSY1 = [
(da['BPXSY1'] < 125),
(da['BPXSY1'] >= 125) & (da['BPXSY1'] <= 174),
(da['BPXSY1'] > 175)
]
conditions_BPXSY2 = [
(da['BPXSY2'] < 125),
(da['BPXSY2'] >= 125) & (da['BPXSY2'] <= 174),
(da['BPXSY2'] > 175)
]
# create a list of the values we want to assign for each condition
values = ['< 125 mm Hg', '125 – 174 mm Hg', '175+ mm Hg']
# create a new column and use np.select to assign values to it using our lists as arguments
#da.dropna(inplace=True)
da['BPXSY1x'] = np.select(conditions_BPXSY1, values)
da['BPXSY2x'] = np.select(conditions_BPXSY2, values)
f, axes = plt.subplots(1, 2, figsize=(13, 6))
sns.boxplot(x="BPXSY1x", y="BPXSY1", data=da, order=['< 125 mm Hg', '125 – 174 mm Hg', '175+ mm Hg'], orient='v' , ax=axes[0])
sns.boxplot(x="BPXSY2x", y="BPXSY2", data=da, order=['< 125 mm Hg', '125 – 174 mm Hg', '175+ mm Hg'], orient='v' , ax=axes[1])
这是结果:
但是,我希望得到的结果看起来像J是BPXSY1,R是BPXSY2(当然,我没有S)
答案 0 :(得分:2)
'BPXSY1'
和'BPXSY2'
。pandas.DataFrame.stack
pandas.cut
对血压值进行分类和标记。import pandas as pd
import seaborn as sns
# given dataframe df
bpxsy1 bpxsy2
0 74 70.0
1 74 72.0
2 78 76.0
# stack the data columns
df = df.stack().reset_index(level=1).rename(columns={'level_1': 'stdy', 0: 'bp'}).reset_index(drop=True)
# display(df)
stdy bp
0 bpxsy1 74.0
1 bpxsy2 70.0
2 bpxsy1 74.0
# bin the measurement values
bins = [0, 125, 150, 175]
labels = ['< 125 mm Hg', '125 - 150 mm Hg', '150+ mm Hg']
df['bins'] = pd.cut(df.bp, bins=bins, labels=labels, right=False)
# display(df)
stdy bp bins
0 bpxsy1 74.0 < 125 mm Hg
1 bpxsy2 70.0 < 125 mm Hg
2 bpxsy1 74.0 < 125 mm Hg
# plot
plt.figure(figsize=(9, 7))
sns.boxplot(x='bins', y='bp', hue='stdy', data=df)