3
我正在使用Facebook Insights API获取数据,并且我得到的数据中有嵌套的列。我尝试按索引分隔它们,但失败了。
要分割的列:
[{'action_type': 'link_click', 'value': '1'}, {'action_type': 'video_view', 'value': '1'}]
我要翻译的状态:
actions_video_view actions_link_click
1 1
xx = dataframe['actions'].apply(pd.Series).merge(dataframe["index"],
right_index=True,
left_index=True).melt(id_vars=['index'],
value_name='actions')
xx2 = xx['action_type'].apply(pd.Series).merge(xx["index"],
right_index=True,
left_index=True)
xx2 = xx2.loc[xx2['action_type'] == 'video_view', ["value", "index"]]
当我运行这段代码时,我得到以下错误:
Traceback (most recent call last):
File "C:ProgramDataAnaconda3libsite-packagespandascoreframe.py", line 3458, in __getitem__
indexer = self.columns.get_loc(key)
File "C:ProgramDataAnaconda3libsite-packagespandascoreindexesbase.py", line 3363, in get_loc
raise KeyError(key) from err
KeyError: 'action_type'
我想根据键分离列并将其添加为数据框列,我可以使用哪种方式?
在数据中显示的示例:
actions
[{'action_type': 'link_click', 'value': '1'}, {'action_type': 'video_view', 'value': '1'}]
[{'action_type': 'link_click', 'value': '3'}, {'action_type': 'video_view', 'value': '3'}]
[{'action_type': 'link_click', 'value': '5'}, {'action_type': 'video_view', 'value': '5'}]
[{'action_type': 'link_click', 'value': '6'}, {'action_type': 'video_view', 'value': '6'}]
[{'action_type': 'link_click', 'value': '7'}, {'action_type': 'video_view', 'value': '7'}]
如果我想应用:
actions_link_click actions_video_view
1 1
3 3
5 5
6 6
7 7
我认为您应该看看数据框的每一行是如何生成的。我认为这不是直截了当的。但对于你目前的问题,这里有一个解决方案:
import pandas as pd
import json
def convert_df(col):
tmp = col.apply(pd.Series)
out = (tmp.assign(idx=tmp.groupby('action_type').cumcount())
.pivot(index='idx', columns='action_type', values='value')
.add_prefix('actions_').rename_axis(columns=None).reset_index(drop=True))
return out
rows = [[{'action_type': 'link_click', 'value': '1'}, {'action_type': 'video_view', 'value': '1'}],
[{'action_type': 'link_click', 'value': '3'}, {'action_type': 'video_view', 'value': '3'}],
[{'action_type': 'link_click', 'value': '5'}, {'action_type': 'video_view', 'value': '5'}],
[{'action_type': 'link_click', 'value': '6'}, {'action_type': 'video_view', 'value': '6'}],
[{'action_type': 'link_click', 'value': '7'}, {'action_type': 'video_view', 'value': '7'}],]
df = pd.DataFrame({'actions' : rows})
df = pd.json_normalize(df['actions'])
df = pd.concat([
convert_df(df[0]),
convert_df(df[1])
], axis=1)
print(df)
actions_link_click actions_video_view
0 1 1
1 3 3
2 5 5
3 6 6
4 7 7
这就行了,
grouped_df = df.groupby("action_type")
new_df = pd.DataFrame([])
for action in df["action_type"].unique():
new_df[f"actions_{action}"] = list(grouped_df.get_group(action)["value"])
输出——
actions_video_view相关内容
- 使用pandas.json_normalize "unfold"字典列表的字典
- 将字典列表转换为Ansible中的字符串列表
- 如何使用我想要获取的字典的一个键/值对从字典列表中访问字典
- 如何在字典列表中格式化字典对象?
- 如何从保留顺序的Python字典列表中删除重复值?
- Ansible:通过数据操作将list的内容转换为字典列表
- 在python中使用if value条件从字典列表中删除一个键
- 平坦字典列表
- 用对应的值替换字典列表中的空值
- 如何使用Python根据匹配的键值在字典列表中添加其他数据?
- 当数据嵌套且具有不规则模式时,将字典列表转换为pandas数据框架
- 如何从包含单个字典列表的系列中创建DataFrame
- 遍历字典列表并打印消息
- 使用panda数据框架有效地获取与条目是否存在于字典列表相关的布尔值列表
- 到/从列表的字典的字典列表,但具有所有可能的排列
- 在python中格式化2个字典列表
- 在字典列表中高效地复制字典对(键、值),并尊重顺序
- 如何将表编码为字典列表直接写入包含CSV的压缩存档?
- 如何将' docker ps '命令格式化为字典列表
- 转换hydra/omegaconf配置python嵌套字典/列表?
最新更新
- 使用# id更改HTML模板中的JS代码值
- Regex语句,用于捕获最外层括号内的元素
- 如何在用户猜测/输入后更改占位符?
- 是否有一种方法来创建一个DataFrame从特定的颜色编码行是在谷歌工作表?(长颈鹿和熊猫)
- AWS Glue: SCRAM认证需要libpq版本10或以上[Using CockroachDB]
- 如何使用信号协议加密/解密?
- pandas dataframe在特定列中的列表值满足一定条件时获取行
- &16 在此 MySQL 查询中做什么?
- 是否有办法使类名作为一个变量?.. Parent_class *p_derived = new classnameher
- 错误:未能将一些参考推入' path '
- 我如何让matplotlib正确格式化这些datetime64对象?
- 如何删除重复的行基于多列值在亚马逊雅典娜?
- 无法"npm install"项目
- Applescript在文件夹中搜索带有关键字的照片
- 在CocoaPods任务中运行管道时出错
- 我是如何设法在通常的 conf 设置之外定义一个 XAMPP Apache 额外目录的?找不到证据
- 我的主要分支是错误的,我想用另一个分支重写它,我怎么能做这样的事情?
- 防止在for循环中展开的函数的形参中展开变量
- 自动伸缩组实例未在ALB上注册
- 我有一个问题与基础SQLITE3,如何解决它?
- react useEffect(): Hello只记录一次
- ViewBinding within Broadcast Receiver
- 为什么x输入事件不再被Tk事件回调处理(Ubuntu 22.04, Tk 8.6.12)?
- 如何降低MSAA内存使用率?
- Apache Flink -匹配具有相同值的字段
- 如何在jquery中添加?
- 如何在AVAudioPCMBuffer上做偏移?
- 定义函数以返回类的属性需要什么?
- Php对象组数组
- 如何用Angular/Javascript创建工作流图
热门标签:
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