首页 > 解决方案 > 使用 apply 计算大量附加列 pandas 数据框

问题描述

我有一个包含 2 列的数据框 - 索引、文本块。我希望创建 50 个额外的列,列名称为从 1980 到 2030 的数字。每一列基本上包含该数字(例如 2015)在文本块中出现的次数。因为我想对每一行都这样做,所以我可以使用这个.apply()函数。

这是功能。

def funct(row):
    mydict = {}
    to_return_list = []
    textcont = row['textblock']
    for no in range(1980,2031):
        mydict[no] = textcont.count(no)
        to_return_list.append(textcont.count(no))

    return tuple(to_return_list)
    # or maybe return pd.Series(mydict) ? 

通常,如果我希望通过在 pandas 中应用函数来计算附加列,代码是:

(df['col1'], df['col2'], df['col3']) = zip(*dfs.apply(funct, axis=1))

如果我希望对我的函数做同样的事情,我将不得不手动添加列名,即

(df['1980'], df['1981'], df['1982'] .... ) = zip(*dfs.apply(funct, axis=1))

这显然非常麻烦。(另外,如果我以后希望将范围更改为:1970 到 2030,我必须再次手动添加名称)。有没有办法在不手动输入名称的情况下做到这一点,也许使用字典?

玩具示例:

import pandas as pd
dataframe = pd.DataFrame([{'index' : 541, 'textblock' : '2019, 2713, hello there general 3120 1980 to 2020'}, {'index' : 6361, 'textblock' : 'Here is some more 2000 dummy text 2029 and additional 1975 text'}])

我解释的输出应该有以下列

index | textblock | 1980 | 1981 ..... | 2030

评论:我不喜欢手动遍历每一行的解决方案。这只是一个突出我的问题的玩具示例。我的原始数据框也有超过 20 列包含其他数据,因此必须创建一个新字典来复制现有数据仍然不是很优雅,尽管任何有效的解决方案都会受到赞赏。

标签: pythonpandasdataframe

解决方案


这是我的建议:

for no in range(1980,2031):
    df[i]=df.textblock.apply(lambda x: x.count(str(i)))

推荐阅读