【问题标题】:group by two columns based on created column根据创建的列按两列分组
【发布时间】:2021-04-30 16:19:03
【问题描述】:

我有一个这样的数据集

df = pd.DataFrame({'time':['13:30', '9:20', '18:12', '19:00', '11:20', '13:30', '15:20', '17:12', '16:00', '8:20'],
               'item': [coffee, bread, pizza, rice, soup, coffee, bread, pizza, rice, soup]})

我想将时间分成早餐、午餐、晚餐的 3 次用餐时间。并将其添加到数据中

我是这样做的

df['hour'] = df.Time.apply(lambda x: int(x.split(':')[0]))
def time_period(hour):
if hour >= 6 and hour < 11:
    return 'breakfast'
elif hour >= 11 and hour < 15:
    return 'lunch'
else:
    return 'dinner'
df['meal'] = df['hour'].apply(lambda x: time_period(x))

现在我想根据这三餐对数据进行分组,并得到如下输出:

【问题讨论】:

  • df2 = df.groupby([df.meal, df.item]).count() 你在找类似的东西吗?

标签: python pandas group-by jupyter-notebook


【解决方案1】:

它看起来并不完全符合您的预期输出,但它遵循相同的想法:

>>> df.groupby("meal")["item"].value_counts()
meal       item  
breakfast  bread     1
           soup      1
dinner     pizza     2
           rice      2
           bread     1
lunch      coffee    2
           soup      1

【讨论】:

    【解决方案2】:
    df['time'] = df['time'].replace(r'[:]','.',regex=True).astype(float)
    df['meal'] = pd.cut(df['time'],bins = [6,11,15,24],labels = ['breakfast','lunch','dinner'])
    a = df.groupby(['meal','item']).size()
    l = []
    for i in np.sort(a.index.get_level_values(level=0).unique().tolist()):
        l.append(a.loc[i].reset_index().rename(columns = {0:'count'}))
    b = pd.concat(l,axis=1)
    c = [i for i in a.index.get_level_values(level=0).unique().tolist()*2]
    c = np.sort(c)
    b.columns = [c,b.columns]
    

    【讨论】:

    • ValueError: 'meal' 既是索引级别又是列标签,有歧义。
    • 也许可以尝试不使用前两行代码,因为您似乎已经有代码可以获取meal
    • 是的,确实如此,您知道如何根据早餐数量对表格进行排序吗?
    猜你喜欢
    • 2022-01-08
    • 2018-12-09
    • 1970-01-01
    • 2019-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多