如何按间隔分隔数据帧列,以及如何打印

2024-09-30 14:33:05 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个如下所示的数据帧:

     Edades
0        -15.612896
1        -18.612896
2         11.387104
3        -12.612896
4         17.387104
            ...
566597    15.387104
566598     5.387104
566599     6.387104
566600     0.387104
566601    22.387104

我想做一个条形图,显示按照标准偏差倍数定义的区间分类的数据频率。到目前为止,我知道plt.hist()实际上可以做类似的事情,但它不允许我在范围上使用浮点类型的值

我尝试的代码如下所示:

plt.figure("Edad_Distrib")
plt.hist(nuevo_edad, range(-100,100))
plt.xlabel("Edades")
plt.ylabel("Frecuencia")
plt.title("Distrib edades")
plt.show()

如何在这样的范围内绘制某个对象

plt.hist(nuevo_edad, range(-2*stdev,2*stdev))

如果它有任何用途的话,我有一段代码,我的教授在R中做的代码,这段代码就是用随机生成的数据帧实现的,我只是不知道如何用python和我特定的数据帧实现它

A <- rnorm(100)
m <- mean(A)
s <- var(A)
k <- -11

x = seq(-5, 5, length = k)
y = vector("numeric", length = (k-1))

for (i in 1:(k-1)){
       y[i] = sum(A>x[i] & A<x[i+1])

}

barplot(y)


Tags: 数据代码定义rangepltlengthhist条形图
2条回答
  • df.a.mean() ± df.a.std() * value定义箱子边缘
    • 下面代码中的列表将创建一个箱子边列表
  • 使用^{}获取数据帧的平均值
  • ^{}得到平均值的标准偏差
import pandas as pd
import numpy as np  # for sample data
import matplotlib.pyplot as plt

# create sample dataframe
np.random.seed(365)
data = {'a': [np.random.randint(700) for _ in range(3000)]}
df = pd.DataFrame(data)

# create the bin edges
bins = [df.a.mean() + (df.a.std() * v) for v in range(-5, 6, 1)]

print(bins)
[-652.44, -451.49, -250.55, -49.6, 151.35, 352.3, 553.25, 754.19, 955.14, 1156.09, 1357.04]
  • 若要手动对数据帧进行装箱,请groupby装箱,并生成条形图
  • 使用^{}创建一个包含容器的新列
# create a column of bins
df['bins'] = pd.cut(df.a, bins=bins)

# groupby the bins and plot
df.groupby('bins')['a'].count().plot.bar()

enter image description here

# matplotlib plot
plt.hist(x=df.a, bins=bins)
plt.ylabel('Frequency')
plt.show()

# or dataframe plot
df.a.plot.hist(bins=bins)
plt.show()

enter image description here

如果要定义一个范围,最常用的方法是将其传递给函数作为keyword argumentkwarg),在本例中为range。它将是这样的:

plt.hist(nuevo_edad, range=(-2*stdev,2*stdev))

请注意,您不会传递集合(作为range(a, b))。在hist中的参数range是两个元素的元组

PS:这只影响要绘制的数据。如果您不是指直方图中需要多少条,请使用参数bins

例如:

plt.hist(nuevo_edad, bins=20, range=(-2*stdev,2*stdev))

这将绘制分布在20条中的-2*stdev2*stdev之间的所有数据

相关问题 更多 >