【问题标题】:Making a bar chart to represent the number of occurrences in a Pandas Series制作一个条形图来表示熊猫系列中的出现次数
【发布时间】:2019-04-27 03:54:04
【问题描述】:

我想知道是否有人可以帮助我制作条形图来显示 Pandas 系列中值的频率。

我从形状为 (2000, 7) 的 Pandas DataFrame 开始,然后从那里提取最后一列。该列是形状 (2000,)。

我提到的系列中的条目从 0 到 17 不等,每个都有不同的频率,我尝试使用条形图绘制它们,但遇到了一些困难。这是我的代码:

# First, I counted the number of occurrences.

count = np.zeros(max(data_val))

for i in range(count.shape[0]):
    for j in range(data_val.shape[0]):
        if (i == data_val[j]):
            count[i] = count[i] + 1

'''
This gives us
count = array([192., 105., ... 19.])
'''

temp = np.arange(0, 18, 1) # Array for the x-axis.

plt.bar(temp, count)

我在最后一行代码中遇到错误,说the objects cannot be broadcast to a single shape.

我最终想要的是一个条形图,其中每个条形对应一个从 0 到 17 的整数值,每个条形的高度(即 y 轴)代表频率。

谢谢。


更新

我决定使用人们在下面给出的建议发布固定代码,以防万一以后遇到类似问题的人能够看到我修改后的代码。

data = pd.read_csv("./data/train.csv") # Original data is a (2000, 7) DataFrame
# data contains 6 feature columns and 1 target column.

# Separate the design matrix from the target labels.
X = data.iloc[:, :-1]
y = data['target']


'''
The next line of code uses pandas.Series.value_counts() on y in order to count
the number of occurrences for each label, and then proceeds to sort these according to
index (i.e. label).

You can also use pandas.DataFrame.sort_values() instead if you're interested in sorting
according to the number of frequencies rather than labels.
'''
y.value_counts().sort_index().plot.bar(x='Target Value', y='Number of Occurrences')

如果我们使用 Pandas 库中内置的方法,则无需使用 for 循环。

回答中提到的具体方法有pandas.Series.values_count()pandas.DataFrame.sort_index()pandas.DataFrame.plot.bar()

【问题讨论】:

    标签: python pandas bar-chart


    【解决方案1】:

    我相信你需要value_countsSeries.plot.bar

    df = pd.DataFrame({
             'a':[4,5,4,5,5,4],
             'b':[7,8,9,4,2,3],
             'c':[1,3,5,7,1,0],
             'd':[1,1,6,1,6,5],
    })
    
    print (df)
       a  b  c  d
    0  4  7  1  1
    1  5  8  3  1
    2  4  9  5  6
    3  5  4  7  1
    4  5  2  1  6
    5  4  3  0  5
    
    
    df['d'].value_counts(sort=False).plot.bar()
    

    如果可能缺少某些值,需要将其设置为0 添加reindex

    df['d'].value_counts(sort=False).reindex(np.arange(18), fill_value=0).plot.bar()
    

    详情

    print (df['d'].value_counts(sort=False))
    1    3
    5    1
    6    2
    Name: d, dtype: int64
    
    print (df['d'].value_counts(sort=False).reindex(np.arange(18), fill_value=0))
    0     0
    1     3
    2     0
    3     0
    4     0
    5     1
    6     2
    7     0
    8     0
    9     0
    10    0
    11    0
    12    0
    13    0
    14    0
    15    0
    16    0
    17    0
    Name: d, dtype: int64
    

    【讨论】:

    • 您的回答对我帮助很大!我不知道 Pandas 有这些方法并且不必要地使用了循环。我也碰巧使用pandas.DataFrame.sort_index() 也得到了我想要的结果。
    【解决方案2】:

    这是一种使用Seaborn的方法

    import numpy as np
    import pandas as pd
    import seaborn as sns
    
    s = pd.Series(np.random.choice(17, 10))
    s
    # 0    10
    # 1    13
    # 2    12
    # 3     0
    # 4     0
    # 5     5
    # 6    13
    # 7     9
    # 8    11
    # 9     0
    # dtype: int64
    
    val, cnt = np.unique(s, return_counts=True)
    val, cnt
    # (array([ 0,  5,  9, 10, 11, 12, 13]), array([3, 1, 1, 1, 1, 1, 2]))
    
    sns.barplot(val, cnt)
    

    【讨论】:

    • 感谢您的回答!我之前实际上从未听说过Seaborn,但将来会看看它。再次感谢。
    猜你喜欢
    • 2017-04-18
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 2020-07-24
    • 2019-04-13
    • 2019-04-30
    • 2023-01-17
    相关资源
    最近更新 更多