【问题标题】:Create a matrix with a set of ranges in columns and a set of ranges in rows with Pandas使用 Pandas 创建一个矩阵,其中包含一组列范围和一组行范围
【发布时间】:2020-05-01 00:22:21
【问题描述】:

我有一个数据框,其中一列“F”的值从 0 到 100,第二列“E”的值从 0 到 500。我想创建一个矩阵,其中的频率在两个范围内F'和'E'。例如,我想知道“F”在 20 到 30 范围内的频率,“E”在 400 到 500 范围内的频率。

我期望得到的是以下矩阵:

matrix of ranges

我尝试使用 pd.cut() 和 groupby() 对范围进行分组,但我不知道如何加入数据。

非常感谢您在使用 pandas 创建矩阵方面提供的帮助。

【问题讨论】:

  • 您能否展示您的代码以及您尝试过的内容,以便我们提供帮助

标签: python pandas range pandas-groupby


【解决方案1】:

您可以使用 cut 函数为每列创建 bin“标签/名称”。 在你对数据框进行旋转之后。

df['rows'] = pd.cut(df['F'], 5) 
df['cols'] = pd.cut(df['E'], 5) 
df = df.groupby(['rows', 'cols']).agg('sum').reset_index([0,1], False) # your agg func here
df = df.pivot(columns='cols', index='rows')

【讨论】:

  • 非常感谢@usher!你的回答是正确的,我正在努力。枢轴函数非常适合创建矩阵!
【解决方案2】:

所以这就是我发现创建矩阵的方式,这显然是受到@usher 回答的启发。我知道它更令人费解,但想分享它。再次感谢@usher

E=df.E
F=df.F

bins_E=pd.cut(E, bins=(max(E)-min(E))/100)
bins_F=pd.cut(F, bins=(max(F)-min(F))/10)

bins_EF=bins_E.to_frame().join(bins_F)
freq_EF=bins_EF.groupby(['E', 'F']).size().reset_index(name="counts")
Mat_FE = freq_EF.pivot(columns='E', index='F')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多