Pyspark:显示数据框列的直方图

问题描述 投票:14回答:5

在pandas数据框中,我使用以下代码绘制列的直方图:

my_df.hist(column = 'field_1')

在pyspark数据框架中是否有可以实现相同目标的东西? (我在Jupyter笔记本中)谢谢!

python pyspark spark-dataframe jupyter-notebook
5个回答
20
投票

不幸的是,我不认为PySpark Dataframes API中有一个干净的plot()hist()函数,但我希望事情最终能朝这个方向发展。

目前,您可以在Spark中计算直方图,并将计算出的直方图绘制为条形图。例:

import pandas as pd
import pyspark.sql as sparksql

# Let's use UCLA's college admission dataset
file_name = "https://stats.idre.ucla.edu/stat/data/binary.csv"

# Creating a pandas dataframe from Sample Data
df_pd = pd.read_csv(file_name)

sql_context = sparksql.SQLcontext(sc)

# Creating a Spark DataFrame from a pandas dataframe
df_spark = sql_context.createDataFrame(df_pd)

df_spark.show(5)

这就是数据的样子:

Out[]:    +-----+---+----+----+
          |admit|gre| gpa|rank|
          +-----+---+----+----+
          |    0|380|3.61|   3|
          |    1|660|3.67|   3|
          |    1|800| 4.0|   1|
          |    1|640|3.19|   4|
          |    0|520|2.93|   4|
          +-----+---+----+----+
          only showing top 5 rows


# This is what we want
df_pandas.hist('gre');

Histogram when plotted in using df_pandas.hist()

# Doing the heavy lifting in Spark. We could leverage the `histogram` function from the RDD api

gre_histogram = df_spark.select('gre').rdd.flatMap(lambda x: x).histogram(11)

# Loading the Computed Histogram into a Pandas Dataframe for plotting
pd.DataFrame(
    list(zip(*gre_histogram)), 
    columns=['bin', 'frequency']
).set_index(
    'bin'
).plot(kind='bar');

Histogram computed by using RDD.histogram()


7
投票

您现在可以使用pyspark_dist_explore包来利用Spark DataFrames的matplotlib hist函数:

from pyspark_dist_explore import hist
import matplotlib.pyplot as plt

fig, ax = plt.subplots()
hist(ax, data_frame, bins = 20, color=['red'])

该库使用rdd直方图函数来计算bin值。


1
投票

用于RDD的histogram方法返回bin范围和bin计数。这是一个获取此直​​方图数据并将其绘制为直方图的函数。

import numpy as np
import matplotlib.pyplot as mplt
import matplotlib.ticker as mtick

def plotHistogramData(data):
    binSides, binCounts = data

    N = len(binCounts)
    ind = np.arange(N)
    width = 1

    fig, ax = mplt.subplots()
    rects1 = ax.bar(ind+0.5, binCounts, width, color='b')

    ax.set_ylabel('Frequencies')
    ax.set_title('Histogram')
    ax.set_xticks(np.arange(N+1))
    ax.set_xticklabels(binSides)
    ax.xaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))
    ax.yaxis.set_major_formatter(mtick.FormatStrFormatter('%.2e'))

    mplt.show()

(此代码假定箱具有相同的长度。)


0
投票

另一种解决方案,无需额外进口,这也应该是有效的;首先,使用窗口分区:

import pyspark.sql.functions as F
import pyspark.sql as SQL
win = SQL.Window.partitionBy('column_of_values')

然后你需要它来使用由窗口分区的计数聚合:

df.select(F.count('column_of_values').over(win).alias('histogram'))

聚合运算符发生在集群的每个分区上,并且不需要额外的主机往返。


0
投票

这很简单,效果很好。

df.groupby(
  '<group-index>'
).count().select(
  'count'
).rdd.flatMap(
  lambda x: x
).histogram(20)
© www.soinside.com 2019 - 2024. All rights reserved.