【问题标题】:Pandas - Groupby find groups within groupsPandas - Groupby 在组内查找组
【发布时间】:2019-07-28 12:09:48
【问题描述】:

这是我开始的link 的转贴,但我意识到问题要复杂得多。

df = pd.DataFrame({'a': ['A1', 'A1', 'A1', 'A2', 'A2','A3','A3', 'A4', 'A3', 'A2', "A4", "A4", "A4"],
                   'value': ["7:00","10:00","20:00","9:00","7:00","9:00","8:00","15:00","19:00", "9:30", "15:30", "16:00", "16:30"],
                   "value2": [3,1,2,4,2,3,3,5,3,2,1,5,7],
                   'value3': ["Apple", "Orange", "Apple", "Kiwi", "Orange", "Orange", "Apple", "Apple", "Apple", "Apple", "Orange", "Orange","Apple"],
                  "value4": ["Throw", "Eat", 'Throw', "Keep", "Eat", "Eat", "Throw", "Throw", "Throw", "Throw", "Eat", "Eat", "Chuck"]})

我想要的是:1)通过ID(变量“a”),选择“value3”下的所有实例,其中它是“orange”,然后是“apple”。他们不必背靠背;这两者之间可以有许多其他值。但是橙子必须及时出现在苹果之前。

2) 然后将这些橙子和苹果的实例分为两组:1) 一组是橙子的 value2 = 1 时; 2) 是橙色不等于 1 时(因此其余归为一组)。 问题是 A4,其中有两个橙子 - 1 和 5。这应该归类在组 value2 = 1 中,因为它发生在时间上。

更新:抱歉 - 我的预期回复似乎没有剪切和粘贴:

value2     value3     count
1          orange     2
all other  orange     2

【问题讨论】:

  • 你能发布预期的结果吗?
  • 我很抱歉 - 无论出于何种原因,它都没有从我的工作区复制过来。请查看更新后的回复。

标签: python pandas


【解决方案1】:

看看这是否可行,但我会看看其他人是否可以给你一个简单而简短的版本,

    df1 = df[['a','value3']].drop_duplicates()
##Merging the dataframes
merge =df1.merge(df,how = 'left',left_index=True, right_index=True)
##Selecting the only requried columns
merge = merge[['value2','value3_x']]
##Renaming the columns
merge = merge.rename(columns={'value3_x':'value3'})
##Filtering the data
merge = merge[merge.value3=='Orange']
##Converting te value to string
merge['value2']= df.value2.astype(str) 
## Changing the value of value2
merge['value2'] = merge.value2.apply(lambda x: '1' if x == '1' else 'all other')
##Grouping the data
merge.groupby(['value2','value3']).value3.count()

【讨论】:

    猜你喜欢
    • 2015-03-06
    • 2020-05-05
    • 1970-01-01
    • 2019-06-08
    • 1970-01-01
    • 1970-01-01
    • 2017-11-30
    • 2021-05-09
    • 2021-09-23
    相关资源
    最近更新 更多