python - 升序/重置多索引 Pandas 的整数值

标签 python pandas

我有一个数据框:

import pandas as pd

tuples = [('a', 1990),('a', 1994),('a',1996),('b',1992),('b',1997),('c',2001)]
index = pd.MultiIndex.from_tuples(tuples, names = ['Type', 'Year'])
vals = ['This','That','SomeName','This','SomeOtherName','SomeThirdName']
df = pd.DataFrame(vals, index=index, columns=['Whatev'])


df
Out[3]: 
                  Whatev
Type Year               
a    1990           This
     1994           That
     1996       SomeName
b    1992           This
     1997  SomeOtherName
c    2001  SomeThirdName

我想添加一列与“年份”相对应的升序整数,该列会针对每个“类型”重置,如下所示:

                  Whatev  IndexInt
Type Year                         
a    1990           This         1
     1994           That         2
     1996       SomeName         3
b    1992           This         1
     1997  SomeOtherName         2
c    2001  SomeThirdName         1

这是我当前的方法:

grouped = df.groupby(level=0)
unique_loc = []
for name, group in grouped:
    unique_loc += range(1,len(group)+1)
joined['IndexInt'] = unique_loc

但这对我来说似乎丑陋且令人费解,我想它在我正在使用的约 5000 万行数据帧上可能会变慢。有没有更简单的方法?

最佳答案

您可以使用groupby(level=0) + cumcount() :

In [7]: df['IndexInt'] = df.groupby(level=0).cumcount()+1

In [8]: df
Out[8]:
                  Whatev  IndexInt
Type Year
a    1990           This         1
     1994           That         2
     1996       SomeName         3
b    1992           This         1
     1997  SomeOtherName         2
c    2001  SomeThirdName         1

关于python - 升序/重置多索引 Pandas 的整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39004736/

相关文章:

python - 具有多个子域的 Django - 有时会呈现不正确的模板

python - 如何使用 Django 1.11 基于模板的表单渲染将 CSS 类添加到小部件/字段

python - while 循环中的按键识别。 Python

Python 从 tripadvisor 抓取 'things to do'

python - Django:查询集对象过滤器,针对另一个对象的时间范围

python - 将时间序列数据集中的随机值设为零

python - 使用 pandas 和 numpy 平均表索引

python - 提取 pandas 字符串字段中出现的两个 url

python - 计算一个 DataFrame 中的条件值并将结果添加到另一个 DataFrame

python - 如何在 Pandas 中将日期舍入到周开始