【问题标题】:computing spell lengths of data based on equality in pandas根据 pandas 中的相等性计算数据的拼写长度
【发布时间】:2014-08-12 15:20:56
【问题描述】:

我想根据 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 年的咒语。

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

【问题讨论】:

  • 我已多次阅读您的问题,但我不明白您在问什么以及想要的输出,您能否通过示例更清楚地解释一下
  • @EdChum 已更新。谢谢

标签: python pandas


【解决方案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

【讨论】:

    【解决方案2】:

    我更新了 @EdChum 建议的 num_spells 并增加了对 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
    

    【讨论】:

      猜你喜欢
      • 2015-06-20
      • 2022-10-24
      • 1970-01-01
      • 2019-07-23
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 2015-07-03
      • 2020-05-08
      相关资源
      最近更新 更多