- mongodb - 在 MongoDB mapreduce 中,如何展平值对象?
- javascript - 对象传播与 Object.assign
- html - 输入类型 ="submit"Vs 按钮标签它们可以互换吗?
- sql - 使用 MongoDB 而不是 MS SQL Server 的优缺点
在一个具体问题上,假设我有一个 DataFrame DF
word tag count
0 a S 30
1 the S 20
2 a T 60
3 an T 5
4 the T 10
我想为每个“单词”找到“计数”最多的“标签”。所以返回会是这样的
word tag count
1 the S 20
2 a T 60
3 an T 5
我不关心计数列,也不关心订单/索引是原始的还是困惑的。返回字典 {'the' : 'S', ...} 就可以了。
我希望我能做到
DF.groupby(['word']).agg(lambda x: x['tag'][ x['count'].argmax() ] )
但它不起作用。我无法访问列信息。
更抽象地说,agg(function) 中的 function 将其视为什么参数?
顺便说一句,.agg() 和 .aggregate() 一样吗?
非常感谢。
最佳答案
agg
与 aggregate
相同.它是可调用的,传递了 Series
的列(DataFrame
对象) ,一次一个。
您可以使用 idxmax
收集最大的行的索引标签计数:
idx = df.groupby('word')['count'].idxmax()
print(idx)
产量
word
a 2
an 3
the 1
Name: count
然后使用 loc
选择 word
中的那些行和 tag
列:
print(df.loc[idx, ['word', 'tag']])
产量
word tag
2 a T
3 an T
1 the S
请注意 idxmax
返回索引标签。 df.loc
可用于选择行按标签。但是如果索引不是唯一的——也就是说,如果有重复索引标签的行——那么df.loc
将选择带有 idx
中列出的标签的所有行 .所以要小心 df.index.is_unique
是 True
如果您使用 idxmax
与 df.loc
或者,您可以使用 apply
. apply
的可调用对象传递了一个子数据帧,它使您可以访问所有列:
import pandas as pd
df = pd.DataFrame({'word':'a the a an the'.split(),
'tag': list('SSTTT'),
'count': [30, 20, 60, 5, 10]})
print(df.groupby('word').apply(lambda subf: subf['tag'][subf['count'].idxmax()]))
产量
word
a T
an T
the S
使用 idxmax
和 loc
通常比 apply
快,尤其是对于大型 DataFrame。使用 IPython 的 %timeit:
N = 10000
df = pd.DataFrame({'word':'a the a an the'.split()*N,
'tag': list('SSTTT')*N,
'count': [30, 20, 60, 5, 10]*N})
def using_apply(df):
return (df.groupby('word').apply(lambda subf: subf['tag'][subf['count'].idxmax()]))
def using_idxmax_loc(df):
idx = df.groupby('word')['count'].idxmax()
return df.loc[idx, ['word', 'tag']]
In [22]: %timeit using_apply(df)
100 loops, best of 3: 7.68 ms per loop
In [23]: %timeit using_idxmax_loc(df)
100 loops, best of 3: 5.43 ms per loop
如果你想要一个将单词映射到标签的字典,那么你可以使用 set_index
和 to_dict
像这样:
In [36]: df2 = df.loc[idx, ['word', 'tag']].set_index('word')
In [37]: df2
Out[37]:
tag
word
a T
an T
the S
In [38]: df2.to_dict()['tag']
Out[38]: {'a': 'T', 'an': 'T', 'the': 'S'}
关于python pandas, DF.groupby().agg(), agg() 中的列引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15322632/
给定输入: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] 将数字按奇数或偶数分组,然后按小于或大于 5 分组。 预期输出: [[1, 3, 5], [2, 4], [6, 8, 10
编辑: @coldspeed、@wen-ben、@ALollz 指出了我在字符串 np.nan 中犯的新手错误。答案很好,所以我不删除这个问题来保留那些答案。 原文: 我读过这个问题/答案 What'
我试图概括我提出的问题 here . mlb 数据框看起来像 Player Position Salary Year 0 Mike Wit
我认为我不需要共享整个数据框,但基本上,这是有问题的代码行(当然,已经导入了 pandas) divstack = df[df['Competitor']=='Emma Slabach'].group
我面临下一个问题:我有组(按 ID),对于所有这些组,我需要应用以下代码:如果组内位置之间的距离在 3 米以内,则需要将它们添加在一起,因此将创建一个新组(代码如何创建我在下面显示的组)。现在,我想要
我有以下数据: ,dateTime,magnitude,occurrence,dateTime_s 1,2017-11-20 08:00:09.052260,12861,1,2017-11-20 08
我按感兴趣的列对 df 进行分组: grouped = df.groupby('columnA') 现在我只想保留至少有 5 名成员的组: grouped.filter(lambda x: len(x
数据是一个时间序列,许多成员 ID 与许多类别相关联: data_df = pd.DataFrame({'Date': ['2018-09-14 00:00:22',
选择 u.UM_TOKEN_NO 、u.UM_FULLNAME、u.SECTOR、u.department_name、t.TS_PROJECT_CODE、sum(t.TS_TOTAL_HRS) 来自
我有这两个表: +---------------+-------------+---------------------+----------+---------+ | items_ordered |
我正在使用 groupby 和 sum 快速汇总两个数据集 一个包含: sequence shares 1 100 2 200 3 50 1 2
这个问题在这里已经有了答案: list around groupby results in empty groups (3 个答案) itertools groupby object not out
我有一组行,我想按标识符的值进行分组 - 存在于每一行中 - 然后对将作为结果的组进行进一步的隔离处理。 我的数据框是这样的: In [50]: df Out[50]: groupkey b
假设您要在全局范围内销售产品,并且希望在某个主要城市的某个地方设立销售办事处。您的决定将完全基于销售数字。 这将是您的(简化的)销售数据: df={ 'Product':'Chair', 'Count
我有一个将数据分组两次的查询: var query = (from a in Context.SetA() from b in Context.SetB().Where(x => x.aId == a
我有一个这种格式的数据框: value identifier 2007-01-01 0.087085 55 2007-01-01 0.703249
这个问题在这里已经有了答案: python groupby behaviour? (3 个答案) 关闭 4 年前。 我有一个这样的列表 [u'201003', u'200403', u'200803
在 Python 中,我可以使用 itertools.groupby 将具有相同键的连续元素分组。 : >>> items = [(1, 2), (1, 5), (1, 3), (2, 9), (3,
无法翻译以下 GroupBy 查询并将引发错误:不支持客户端 GroupBy IEnumerable ids = new List { 1, 2, 3 }; var q = db.Comments.W
考虑一个 Spark DataFrame,其中只有很少的列。目标是对其执行 groupBy 操作,而不将其转换为 Pandas DataFrame。等效的 Pandas groupBy 代码如下所示:
我是一名优秀的程序员,十分优秀!