python-熊猫数据框组:求和一列,取其他列的第一个元素
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python-熊猫数据框组:求和一列,取其他列的第一个元素,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2012字,纯文字阅读大概需要3分钟。
内容图文
![python-熊猫数据框组:求和一列,取其他列的第一个元素](/upload/InfoBanner/zyjiaocheng/690/46d85e91e5f6425e822254279d00e48e.jpg)
我有一个熊猫数据框
x = pd.DataFrame.from_dict({'row':[1, 1, 2, 2, 3, 3, 3], 'add': [1, 2, 3, 4, 5, 6, 7], 'take1': ['a', 'b', 'c', 'd', 'e', 'f', 'g'], 'take2': ['11', '22', '33', '44', '55', '66', '77'], 'range': [100, 200, 300, 400, 500, 600, 700]})
add range row take1 take2
0 1 100 1 a 11
1 2 200 1 b 22
2 3 300 2 c 33
3 4 400 2 d 44
4 5 500 3 e 55
5 6 600 3 f 66
6 7 700 3 g 77
我想按行列将其分组,然后在添加列中添加条目,但从take1和take2中获取第一个条目,然后从范围中选择最小值和最大值:
add row take1 take2 min_range max_range
0 3 1 a 11 100 200
1 7 2 c 33 300 400
2 18 3 e 55 500 700
解决方法:
通过dict使用DataFrameGroupBy.agg,但随后需要进行一些清理,因为在列中获取MultiIndex:
#create a dictionary of column names and functions to apply to that column
d = {'add':'sum', 'take1':'first', 'take2':'first', 'range':['min','max']}
#group by the row column and apply the corresponding aggregation to each
#column as specified in the dictionary d
df = x.groupby('row', as_index=False).agg(d)
#rename some columns
df = df.rename(columns={'first':'', 'sum':''})
df.columns = ['{0[0]}_{0[1]}'.format(x).strip('_') for x in df.columns]
print (df)
row take1 range_min range_max take2 add
0 1 a 100 200 11 3
1 2 c 300 400 33 7
2 3 e 500 700 55 18
详细信息:根据字典中指定的功能汇总列:
df = x.groupby('row', as_index=False).agg(d)
row range take2 take1 add min max first first sum 0 1 100 200 11 a 3 1 2 300 400 33 c 7 2 3 500 700 55 e 18
用“”替换列名总和,将导致
row range take2 take1 add min max 0 1 100 200 11 a 3 1 2 300 400 33 c 7 2 3 500 700 55 e 18
使用字符串格式化程序对列进行列表理解将获得所需的列名称.将其分配给df.columns将获得所需的输出.
内容总结
以上是互联网集市为您收集整理的python-熊猫数据框组:求和一列,取其他列的第一个元素全部内容,希望文章能够帮你解决python-熊猫数据框组:求和一列,取其他列的第一个元素所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。