我正在对一组数据进行分组和计数。
result = sum(int(digit) for digit in str(nums))
输出
df = pd.DataFrame({'key': ['A', 'B', 'A'],
'data': np.ones(3,)})
df.groupby('key').count()
上面的代码虽然有效,但我想知道是否有更简单的代码。
data
key
A 2
B 1
似乎是一个占位符,是必不可少的。
'data': np.ones(3,)
输出
pd.DataFrame(['A', 'B', 'A']).groupby(0).count()
我的问题是,有没有更简单的方法来分别生成'A'和'B'的计数,而没有像A
B
这样的东西?
不一定要使用pandas方法,也可以使用numpy或python原生函数。
答案 0 :(得分:0)
改为使用<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<script type="text/javascript" src="../js/script.js"></script>
<link rel="stylesheet" href="../css/style.css">
<meta charset="utf-8">
<title>Web Mail</title>
</head>
<body>
<nav id="navBar">
<div class="nav-wrapper">
<ul class="left">
<a href="#" data-target="slide-out" class="sidenav-trigger" style="display:block !important"><i class="material-icons">menu</i></a>
</li>
</ul>
<ul class="right">
<li><a href="#!"><i class="material-icons right">archive</i></a>
</li>
<li><a href="#!"><i class="material-icons right">delete</i></a>
</li>
<li><a href="#!"><i class="material-icons right">mail</i></a>
</li>
</ul>
</div>
</nav>
<ul id="slide-out" class="sidenav">
<li>
<div class="user-view">
<div class="background">
<img src="https://static01.nyt.com/images/2018/05/27/sports/27championstrophy/merlin_138716301_7655ceb3-fb5e-4354-821a-bfad8d475786-superJumbo.jpg?quality=90&auto=webp" style="width:100%">
</div>
<a href="#user"><img class="circle" src="https://upload.wikimedia.org/wikipedia/en/thumb/5/56/Real_Madrid_CF.svg/1200px-Real_Madrid_CF.svg.png"></a>
<a href="#name"><span class="white-text name">John Doe </span></a>
<a href="#email"><span class="white-text email">test@gmail.com</span></a>
</div>
</li>
<li><a href="#!"><i class="material-icons">mail_outline</i>Notifications On</a>
<li>
<li><a href="#!"><i class="material-icons">local_phone</i>(XXX)-XXX-XXXX</a>
<li>
<li>
<div class="divider"></div>
</li>
<li><a class="subheader">Mail Functions</a></li>
<a class="waves-effect waves-light btn-small" id="sendMail"><i class="material-icons left">mail</i>Send Mail</a>
<a class="waves-effect waves-light btn-small" id="viewMail"><i class="material-icons left">drafts</i>View Mailbox</a>
</ul>
</body>
</html>
。
Series
答案 1 :(得分:0)
使用defaultdict
:
from collections import defaultdict
data = ['A', 'A', 'B', 'A', 'C', 'C', 'A']
d = defaultdict(int)
for element in data:
d[element] += 1
d # output: defaultdict(int, {'A': 4, 'B': 1, 'C': 2})
答案 2 :(得分:0)
没有任何分组,仅在计数,因此您可以使用
from collections import Counter
counter(['A', 'B', 'A'])