【问题标题】:How do I use booleans to create dataframe and plot the filtered data on pie chart?如何使用布尔值创建数据框并将过滤后的数据绘制在饼图上?
【发布时间】:2021-08-26 11:12:35
【问题描述】:
import pandas as pd
import numpy as np


data = {'City': ['KUMASI', 'ACCRA', 'ACCRA', 'ACCRA', 'KUMASI', 'ACCRA', 'ACCRA', 'ACCRA', 'ACCRA'], 'Building': ['Commercial', 'Commercial', 'Industrial', 'Commercial', 'Industrial', 'Commercial', 'Commercial', 'Commercial', 'Commercial'], 'LPL': ['NC', 'C', 'C', 'C', 'NC', 'C', 'NC', 'NC', 'NC'], 'Lgfd': ['NC', 'C', 'C', 'C', 'NC', 'C', 'NC', 'NC', 'C'], 'Location': ['NC', 'C', 'C', 'C', 'NC', 'C', 'C', 'NC', 'NC'], 'Hazard': ['NC', 'C', 'C', 'C', 'NC', 'C', 'C', 'NC', 'NC'], 'Inspection': ['NC', np.nan, np.nan, np.nan, 'NC', 'NC', 'C', 'C', 'C'], 'Name': ['Zonal', 'In Prog', 'Tullow Oil', 'XGI', 'Food Factory', 'MOH', 'EV', 'CSD', 'Electroland'], 'Air Termination System': ['Vertical Air Termination', 'Vertical Air Termination', 'Vertical Air Termination', 'Early Streamer Emission', 'Vertical Air Termination', 'Vertical Air Termination', 'Vertical Air Termination', 'Vertical Air Termination', 'Early Streamer Emission'], 'Positioned Using': ['Highest Points', 'Software', 'Software', 'Software', 'Highest Points', np.nan, np.nan, 'Rolling Sphere Method', 'Software']}
df = pd.DataFrame(data)

#Filter dataset to return rows with LPL being "C" and Hazard being "C"
filter = df[(df["LPL"] == "C") & (df["Hazard"] == "C")]

#Show number of rows in filter
print(filtered_1["LPL"].value_counts())
print(filtered_1["Hazard"].value_counts())

现在我要做的是绘制一个带有两个标签的饼图。
一个标签是LPL and Hazard being C,另一个标签是LPL and Hazard not being C

基本上,我的意思是,LPL and Hazard being C 相对于总行数的百分比将显示在图表上,LPL and Hazard not being C 也是如此。有人可以帮忙吗?

【问题讨论】:

    标签: python pandas dataframe matplotlib


    【解决方案1】:

    我知道的最简单的方法是计算完整数据帧的长度和过滤后的数据帧的长度:

    LPL_and_hazard_equal_C = len(filtered)
    total_records = len(df)
    LPL_and_harard_different_from_C = total_records - LPL_and_hazard_equal_C
    
    
    fig, ax = plt.subplots()
    
    ax.pie([LPL_and_hazard_equal_C, LPL_and_harard_different_from_C], labels = ['LPL and Hazard being C', 'LPL and Hazard not being C'], autopct = '%.1f%%')
    
    plt.show()
    

    【讨论】:

    • 也许添加类似plt.pie(..., autopct="%.1f")的东西?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-19
    • 2020-05-31
    • 1970-01-01
    相关资源
    最近更新 更多