python - 基于pandas中的相等性计算数据的拼写长度

标签 python pandas

我想根据 pandas 数据框中相邻列的相等性来计算 spell 长度。最好的方法是什么?

一个例子:

import pandas as pd
d1 = pd.DataFrame([['4', '4', '4', '5'], ['23', '23', '24', '24'], ['112', '112', '112', '112']], 
              index=['c1', 'c2', 'c3'], columns=[1962, 1963, 1964, 1965])

生成一个看起来像的数据框

enter image description here

我想返回如下所示的数据框。此输出记录了每行发生的咒语数量。在本例中,c1 有 2 个咒语,第一个咒语发生在 1962 年至 1964 年,第二个咒语在 1965 年开始和结束:

enter image description here

以及一个描述拼写长度的数据框,如下所示。例如,c1 的一个咒语持续时间为 3 年,第二个咒语的持续时间为 1 年。

enter image description here

这种重新编码在生存分析中很有用。

最佳答案

以下内容适用于您的数据集,需要提出一个问题才能减少我对使用 list comprehensions and itertools 的原始答案:

In [153]:

def num_spells(x):
    t = list(x.unique())
    return [t.index(el)+1 for el in x]

d1.apply(num_spells, axis=1)

Out[153]:
    1962  1963  1964  1965
c1     1     1     1     2
c2     1     1     2     2
c3     1     1     1     1

In [144]:
from itertools import chain, repeat
def spell_len(x):
    t = list(x.value_counts())
    return list(chain.from_iterable(repeat(i,i) for i in t))

d1.apply(spell_len, axis=1)
Out[144]:
    1962  1963  1964  1965
c1     3     3     3     1
c2     2     2     2     2
c3     4     4     4     4

关于python - 基于pandas中的相等性计算数据的拼写长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25152470/

相关文章:

python - Pandas 读取带空白的多索引 csv

用于存储和查询地理坐标的 Python 模块

Python 正则表达式 r 前缀后跟三个单(或双)引号

python - 在应用 pandas groupby 后向图中添加条形以显示平均值

python - 添加列并根据 Pandas 中的其他列填充缺失值

python - 如何根据Python中的列值创建自定义数据框?

python - 绘制一个数据框作为许多折线图

python - 调用全局变量时无法解析的引用?

Python:值的总和大于最后一个值

python - Google Geocode api 不返回某些 'direct hit' 地址的 postal_code