gpt4 book ai didi

python - 在 Pandas 中划分直方图

转载 作者:行者123 更新时间:2023-11-28 16:36:40 25 4
gpt4 key购买 nike

我正在通过 pandas 读取一个 csv 文件,并制作如下简单的直方图:

df = pd.read_csv(sys.argv[1],header=0)
hFare = df['Fare'].dropna().hist(bins=[0,10,20,30,45,60,75,100,600],label = "All")
hSurFare = df[df.Survived==1]['Fare'].dropna().hist(bins=[0,10,20,30,45,60,75,100,600],label="Survivors")

我想要的是两个直方图的 bin by bin 比率。有没有简单的方法可以做到这一点?

最佳答案

首先,我们将创建一些示例数据。将来如果您要问有关 pandas 的问题,最好包含示例数据,人们可以轻松地将其复制粘贴到他们的 Python 控制台中:

import pandas as pd
import numpy as np
df = pd.DataFrame({'Fare': np.random.uniform(0, 600, 400),
'Survived': np.random.randint(0, 2, 400)})

然后使用 pd.cut 以与在直方图中相同的方式对数据进行分箱:

df['fare_bin'] = pd.cut(df['Fare'], bins=[0,10,20,30,45,60,75,100,600])

查看每个箱内的总计数和存活计数(您可能会这样做作为单独的列,但我只是快速完成):

df.groupby('fare_bin').apply(lambda g: (g.shape[0], g.loc[g['Survived'] == 1, :].shape[0]))

Out[34]:
fare_bin
(0, 10] (7, 4)
(10, 20] (9, 6)
(100, 600] (326, 156)
(20, 30] (5, 4)
(30, 45] (12, 6)
(45, 60] (15, 11)
(60, 75] (13, 7)
(75, 100] (13, 6)
dtype: object

然后编写一个快速函数来获取比率:

def get_ratio(g):
try:
return float(g.shape[0]) / g.loc[g['Survived'] == 1, :].shape[0]
except ZeroDivisionError:
return np.nan
df.groupby('fare_bin').apply(get_ratio)

Out[30]:
fare_bin
(0, 10] 1.750000
(10, 20] 1.500000
(100, 600] 2.089744
(20, 30] 1.250000
(30, 45] 2.000000
(45, 60] 1.363636
(60, 75] 1.857143
(75, 100] 2.166667
dtype: float64

关于python - 在 Pandas 中划分直方图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25275800/

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