基于等价性的Pandas数据拼写长度计算

2024-04-19 04:06:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据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有两个咒语第一个出现在1962年到1964年,第二个开始和结束于1965年:

enter image description here

以及一个数据帧,它描述了如下所示的咒语长度。例如c1有一个咒语3年,第二个咒语持续时间为1年。你知道吗

enter image description here

这种重新编码在生存分析中是有用的。你知道吗


Tags: 数据方法importdataframepandasindexas咒语
2条回答

以下内容适用于您的数据集,需要提出一个问题才能将我最初的答案简化为使用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

我已经更新了@EdChum建议的num\u拼写,并考虑了np.nan值的存在

def compute_number_of_spells(wide_df):
    """
    Compute Number of Spells in a Wide DataFrame for Each Row
    Columns : Time Data
    """
    def num_spells(x):
        """ Compute the spells in each row """
        t = list(x.dropna().unique())
        r = []
        for el in x:
            if not np.isnan(el):                
                r.append(t.index(el)+1)
            else:
                r.append(np.nan)            #Handle np.nan case
        return r
    wide_df = wide_df.apply(num_spells, axis=1)
    return wide_df

相关问题 更多 >