我想根据 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])
生成一个看起来像的数据框
我想返回如下所示的数据框。此输出记录了每行发生的咒语数量。在本例中,c1
有 2 个咒语,第一个咒语发生在 1962 年至 1964 年,第二个咒语在 1965 年开始和结束:
以及一个描述拼写长度的数据框,如下所示。例如,c1
的一个咒语持续时间为 3 年,第二个咒语的持续时间为 1 年。
这种重新编码在生存分析中很有用。
最佳答案
以下内容适用于您的数据集,需要提出一个问题才能减少我对使用 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/