我有一个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列,其中还包含其他数据,因此必须创建一个新字典来复制现有数据仍然不是很优雅,尽管任何有效的解决方案都将受到赞赏。
- 使用regexp查找所有no.
- 使用
explode
将类列表转换为行,复制索引值 - 然后groupby ['index', 'textblock', 'no']计算大小,然后解栈
pat =r'b%sb' % r'b|b'.join(map(str, range(1980,2031)))
dataframe['no'] = dataframe['textblock'].str.findall(pat)
df = dataframe.explode('no').groupby(['index', 'textblock', 'no']).size().unstack(fill_value=0).reset_index()
df.columns.name = None
print(df)
index textblock 1980 2000 2019
0 541 2019, 2713, hello there general 3120 1980 to 2020 1 0 1
1 6361 Here is some more 2000 dummy text 2029 and add... 0 1 0
2020 2029
0 1 0
1 0 1
我的建议是:
for no in range(1980,2031):
df[i]=df.textblock.apply(lambda x: x.count(str(i)))
**kwargs
toassign()
工作良好
import pandas as pd
df = 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'}])
df2 = df.assign(**{str(c):df.textblock.str.count(str(c)) for c in range(2015,2030)})
相关内容
- SQLAlchemy read_sql() into Pandas dataframe -大的列值被截断
- 如何计数在pandas DataFrame中出现唯一值,并将其保存为新的DataFrame
- 在pandas dataframe中,从%d-%m-%y倒转到%y-%m-%d
- 在python中使用group by从pandas dataframe创建list的列表
- 在Pandas Dataframe中,如何根据列中的已知值获得另一列的索引?
- Pytorch:如何从pandas dataframe中准备1d数据集?
- 过滤/查询多个分组后的Pandas DataFrame /agg
- 移动特定的行以纠正Pandas Dataframe中缺失的值
- Pandas DataFrame -根据子字符串筛选行
- Python Pandas DataFrame -从重复出现的循环索引(groupby, sort)中提取最后的数据.&
- 仅根据列值对pandas Dataframe的部分进行排序
- 迭代子集并计算pandas DataFrame的均值
- 首次组满足pandas DataFrame中的条件
- 在Pandas Dataframe (python)中按时间戳分组数据系列
- 尝试遍历pandas dataframe的行,并在满足条件时编辑行
- python pandas dataframe多列匹配索引或行名
- 创建一个MultiIndex Pandas DataFrame用于术语计数和频率跟踪
- 查找Pandas DataFrame中包含字典的列
- Pandas Dataframe-如果值与其他行的值匹配,则删除某些行(考虑性能)
- 如何在方法链的下一个方法中正确引用以前的Pandas DataFrame ?
最新更新
- 如何在Azure容器应用程序上部署React Python应用程序时解决此错误?
- 如何在不泄露源代码的情况下销售chrome扩展
- wp.blocks.blockRegisterType在控制台显示错误- Gutenberg Wordpress.<
- 物质化在shadowroot内的Modal内初始化自动完成不工作
- 如何使用micronaut实现基于模式的多租户
- 授权非admin用户在Google Apps Script中运行admin SDK
- 需要退出函数,但没有得到一个不允许的值错误
- 合并两个调用并使用typeahead ngx-bootstrap显示结果?
- 如何发送文本和二进制套接字在单一消息在C?
- 我如何隐藏(而不是禁用)在Django admin的动作添加模型按钮在ModelAdmin列表视图?
- AWS CloudFormation:Cognito LambdaTrigger CustomEmailSender - 属性"Not currently supported by AWS Cloud
- Python Discord bot !命令的权限
- GitHub上下文变量未针对可重用工作流引用进行评估
- 停止滑动眼睛.IO克隆,相位器3
- 我正在尝试运行美洲驼索引模型,但是当我进入索引构建步骤时 - 它一次又一次地失败,我该如何解决这个问题?
- 502坏网关与Nginx服务器托管.net核心项目
- LG Hub Script Non-Functional
- c -对齐检查在WebAssembly时,模拟XMM的内在?
- 我的多线程代码与c++不能正常工作
- 如何在SQL数据库行中存储一对多关系?
- 向b-tree索引更新具有相同值的列
- 在c++中,用引号和空格之间的键/值加载文件的最有效方式是什么?
- Java多线程并发与并行
- 在启动画面中淡入和淡出图像
- 多个模型到一个manytomanyfield表
- Javascript-如果array2部分排序为array1,则检查数组
- 为什么我的Biquad过滤器没有从我的噪音正确断开?
- 删除nullptr对象可能调用也可能不调用释放函数.为什么不保证后者呢?
- Azure SQL Hyperscale-0个辅助副本
- 我使用的只是音频在扑动应用程序,从url播放,在真实设备上的一段时间后,应用程序停止,试图在后台播放音频
热门标签:
javascript python java c# php android html jquery c++ css ios sql mysql arrays asp.net json python-3.x ruby-on-rails .net sql-server django objective-c excel regex ruby linux ajax iphone xml vba spring asp.net-mvc database wordpress string postgresql wpf windows xcode bash git oracle list vb.net multithreading eclipse algorithm macos powershell visual-studio image forms numpy scala function api selenium