【问题标题】:How to extract unique permutations from pandas DataSeries?如何从 pandas DataSeries 中提取独特的排列?
【发布时间】:2017-09-11 14:00:26
【问题描述】:

在 Jupyter 中使用 Pandas DataSeries 我有一个包含如下行的数据集:

color: white
engineType: diesel
make: Ford
manufacturingYear: 2004
accidentCount: 123

我需要做的是按制造年份(x 轴)为颜色/engineType/make 的所有排列绘制事故计数图表(y 轴)。任何想法如何进行?

为了加快速度,我进行了以下初始设置:

import numpy as np
import pandas as pd
from pandas import DataFrame, Series
import random


colors = ['white', 'black','silver']
engineTypes = ['diesel', 'petrol']
makes = ['ford', 'mazda', 'subaru']
years = range(2000,2005)

rowCount = 100

def randomEl(data):
    rand_items = [data[random.randrange(len(data))] for item in range(rowCount)]
    return rand_items


df = DataFrame({
    'color': Series(randomEl(colors)),
    'engineType': Series(randomEl(engineTypes)),
    'make': Series(randomEl(makes)),
    'year': Series(randomEl(years)),
    'accidents': Series([int(1000*random.random()) for i in range(rowCount)])
})

【问题讨论】:

    标签: python pandas jupyter data-science


    【解决方案1】:

    您可以使用groupby(),通过唯一的colorengineTypemake 组合获得事故数量:

    accident_counts = df.groupby(['color', 'engineType', 'make'])['accidents'].sum()
    

    Matplotlib 是绘制结果的一种方式:

    import matplotlib.pyplot as plt
    accident_counts.plot(kind='bar')
    plt.show()
    

    【讨论】:

    • 很好的答案。令人惊讶的是,熊猫为您做了多少工作。
    猜你喜欢
    • 2020-07-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-10
    • 2018-05-06
    • 2018-02-03
    • 2019-08-12
    相关资源
    最近更新 更多