python - 创建一个内容为集合的 pandas DataFrame 列
问题描述
我遇到了熊猫问题。
所以这是我的数据框:
user page_number page_parts_of_speech
Anne 1 [('Hi', NP), ('my', PP), ('name', NN), ('is', VB), ('Anne', NP)]
John 2 [('Hi', NP), ('my', PP), ('name', NN), ('is', VB), ('John', NP)]
我想添加一个名为 的新列,set_of_parts_of_speech
其中包含一个集合,该集合包含该parts_of_speech
列中所有与 NP 元组的单词。
示例输出为:
user page_number page_parts_of_speech set_of_parts_of_speech
Anne 1 [('Hi', NP), ('my', PP), ['Hi', 'Anne']
('name', NN), ('is', VB), ('Anne', NP)]
John 2 [('Hi', NP), ('my', PP), ['Hi', 'John']
('name', NN), ('is', VB), ('John', NP)]
set_of_parts_of_speech 列包含一个实际集合非常重要。
对此问题的任何帮助将不胜感激。
解决方案
与列表推导一起使用apply
按条件过滤:
print (type(df.loc[0, 'page_parts_of_speech']))
<class 'list'>
f = lambda x: set([y[0] for y in x if y[1] == 'NP'])
df['set_of_parts_of_speec'] = df['page_parts_of_speech'].apply(f)
print (df)
user page_number page_parts_of_speech \
0 Anne 1 [(Hi, NP), (my, PP), (name, NN), (is, VB), (An...
1 John 2 [(Hi, NP), (my, PP), (name, NN), (is, VB), (Jo...
set_of_parts_of_speec
0 {Hi, Anne}
1 {Hi, John}
推荐阅读
- google-chrome - 在网络选项卡下的检查器中没有看到来自网站的所有流量?
- delphi - 我收到此错误:项目引发异常类 EDatabaseError 并带有消息“sql:未找到字段”
- jquery - jQuery $.noConflict(); 正在阻止我的弹出窗口工作
- tensorflow - 将张量流降级到 v=2.1.0
- java - 给定一个原始数组的对象,确定数组元素的原始类型的最有效方法是什么
- javascript - 如何解决“NodeJS API 调用响应是不可解析的对象”?
- xcode - Xcode12 SwiftUI 项目创建 LaunchScreen 故事板
- telerik - 在 Kendo React DropDownList 中找不到数据
- python - 使用 selenium python 在同一浏览器中打开多个 URL
- jquery - 当禁用连续循环并且滑块无法朝该方向移动时,如何在按钮上添加禁用类?