简体   繁体   English

在 Python 中使用奇数创建行数

[英]Create row count using odd numbers in Python

There has to be a simple solution here.这里必须有一个简单的解决方案。 I know how to use cumcount but I want it to count in odd numbers.我知道如何使用 cumcount 但我希望它以奇数计数。 For example I have the following DF.例如,我有以下 DF。 Searches have been pretty useless as they all pull up counting the "odd" numbers.搜索几乎没有用,因为它们都在计算“奇数”数字。

letters = [ "A", "A", "A", "B", "B", "B"]

df = pd.DataFrame(letters, columns=["letter"])

df['cumcount'] = df.groupby('letter').cumcount() + 1


df =

letter     cumcount  

  A           1
  A           2
  A           3
  B           1
  B           2
  B           3

What I'm looking to do is have the output be this.我要做的是让输出是这样的。

df =

letter     cumcount    odd_count

  A           1            1
  A           2            3
  A           3            5
  B           1            1
  B           2            3
  B           3            5

Lets do some math:让我们做一些数学运算:

df['cumcount'] = df.groupby('letter').cumcount() * 2 + 1

  letter  cumcount
0      A         1
1      A         3
2      A         5
3      B         1
4      B         3
5      B         5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM