python - 文件 csv:如何使用 python 根据其他列值计算值的出现次数?
问题描述
我有一个 .csv 文件(600 行),其中包含一些字段:提交 ID、气味类型等。
我会计算每个提交 ID 的每种气味的出现次数。
我会输出的示例:
commit dfbu3u4498fbbefi: [dense structure :1, cyclic dependency:4, unstable dependency: 67, feature concentration: 6, god component: 8]
commit bifueifyuwefbvwr: [dense structure :34, cyclic dependency:43, unstable dependency: 97, feature concentration: 43, god component: 10]
我试过这个,但我认为我需要另一个循环(也许?)对不起,我以前从未使用过 Python
import csv
import collections
smell = collections.Counter()
with open('Ref.csv') as file:
reader = csv.reader(file, delimiter=';')
for row in reader:
smell[row[0]] += 1
print (smell.most_common(5))
OUTPUT:
[('9b0dd5dc979bd490ae34f6d790c466b47c84c920', 96), ('6431099fe7d5d90da678a78051f12894da82c68d', 96), ('44fdfa7ea93c15bb116a25e0675d98469deafaa6', 96), ('b2c40612a2c60685555f35af71f5801391a58b4b', 96), ('aa6cbb78cca17a9de339b2d060c00352e8beedde', 96)]
or if i change row index to 2 i got
[('Unstable Dependency', 315), ('Feature Concentration', 238), ('God Component', 84), ('Cyclic Dependency', 28), ('Dense Structure', 7)]
解决方案
你可以用pandas
它来做到这一点:
import pandas as pd
# Dataframe definition
df = pd.read_csv('Ref.csv', sep=';')
# Group and get the count values.
df_grouped = df.groupby(by=['commit', 'smell']).size()
df_grouped
现在是 a pandas.series
,如果你想让它dataframe
再次成为 a ,你应该这样做:
df_grouped = df_grouped.reset_index()
df_grouped = df_grouped.rename(columns={0: "counts"})
我强烈建议您查看文档:https ://pandas.pydata.org/pandas-docs/stable/index.html
推荐阅读
- apache - Apache 2.4.6 AH00898:从远程服务器读取错误返回
- reactjs - react-testing-library点击链接标签后不要去另一个页面
- pine-script - Pine Script Strategy - 当*price*(未收盘)超过某个值时如何触发入场?目前进入交易一根蜡烛为时已晚
- python-3.x - Python - 通过 Pillow 打开时,GIF 不移动并且分配了不同的名称
- pandas - pandas 和“'Nontype' 对象不可调用”
- java - 无法在 Android 中使用 SMS OTP 验证
- python - 错误“列表”对象不可调用,在 discord.py 1.6.0 中
- arrays - 使用 Mojolicious::Lite (perl) - 我想将所有参数的列表放入一个简单的@ARRAY
- vba - 收到邮件/outlook/VBA后脚本执行
- zooming - 根据上下文,如何获得允许的最大缩放并相应地设置地图范围