python - pandas:沿着 DataFrame 识别 "portions"

标签 python pandas

我有一个看起来或多或少像这样的数据框:

import pandas as pd
df = pd.DataFrame([list('AAABBBAAA')]).T
df.columns = [ 'type']
print(df)

   type
0     A
1     A
2     A
3     B
4     B
5     B
6     B
7     A
8     A
9     A
10    B

假设我的 DataFrame 已经排序,我的目标是沿着“类型”列识别“连续性”;我会对这样的事情感到高兴:

   type     portion_ID
0     A             A0
1     A             A0
2     A             A0
3     B             B0
4     B             B0
5     B             B0
6     B             B0
7     A             A1
8     A             A1
9     A             A1
10    B             B1

我猜是这样的

df['portion_ID'] = g['type'].apply(lambda s: s + some_magics())

可以解决这个问题,但我没有在任何地方找到“some_magic()”:-)

提前致谢

最佳答案

我想到的第一件事是你可以在对象中保存状态:

class State(object):
    def __init__(self):
        self.current = None
        self.current_label = None
        self.types = {}

def func(row, state):
    t = row['type']
    if state.current != t:
        state.current = t
        state.types[t] = state.types.get(t, -1) + 1
        state.current_label = t + str(state.types[t])
    return state.current_label

>>> df.apply(func, args=(State(),), axis=1)
0     A0
1     A0
2     A0
3     B0
4     B0
5     B0
6     B0
7     A1
8     A1
9     A1
10    B1
dtype: object

如果状态发生变化,您还可以计算包含信息的列,然后仅传递字典作为状态:

df['change'] = ~ (df == df.shift())
def func(row, state):
    t = row['type']
    if row['change']:
        state[t] = state.get(t, -1) + 1
    return t + str(state[t])
df.apply(func, args=({},), axis=1)

关于python - pandas:沿着 DataFrame 识别 "portions",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18617854/

相关文章:

python - 从字符串中去除有序的字符序列

python - 如何让用户指定一个数字而不向我返回错误?

python - 如何恢复预训练模型以初始化参数

python - 将嵌套字典中出现的所有类型提升到顶级键

python - python中的正则表达式

python - 通过组合文本 pandas 制作新的数据框

python - 将对称矩阵加载到 pandas DataFrame 中,其中文件具有 3 列格式(行、列、数据)

python - 在 python 3.7 中安装 pandas

python - Groupby 并从组 : Pandas 的最小值中找出差异

python - 连接年份和季度的新变量