You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将TikTokApi返回的多个Python字典转换为Pandas DataFrame?

解决方案

要将TikTokApi返回的用户字典转换为指定格式的Pandas DataFrame,按以下步骤修改代码即可:

步骤说明

  1. 导入Pandas库:引入pandas用于创建和处理DataFrame。
  2. 收集用户数据:循环遍历视频时,将每个用户的字典存入列表,而非直接打印。
  3. 去重用户数据:同一个用户可能发布多条带目标hashtag的视频,通过uniqueId去重避免重复数据。
  4. 生成DataFrame:用Pandas将整理后的字典列表转换为DataFrame,按需设置列对齐样式匹配预期格式。

修改后的完整代码

from TikTokApi import TikTokApi
import pandas as pd

hashtag = "ugc"
count = 10

# 存储用户字典的列表
user_list = []

with TikTokApi() as api:
    tag = api.hashtag(name=hashtag)
    print(tag.info())

    for video in tag.videos(count=count):
        user_dict = video.author.as_dict
        user_list.append(user_dict)

# 去重:根据uniqueId保留唯一用户
seen_unique_ids = set()
unique_users = []
for user in user_list:
    if user['uniqueId'] not in seen_unique_ids:
        seen_unique_ids.add(user['uniqueId'])
        unique_users.append(user)

# 转换为DataFrame
df = pd.DataFrame(unique_users)

# 可选:设置列对齐样式,匹配你期望的格式
styled_df = df.style.set_properties(**{
    'text-align': 'left'
}).set_table_styles([
    {'selector': 'th:nth-child(2)', 'props': [('text-align', 'center')]},
    {'selector': 'th:nth-child(3)', 'props': [('text-align', 'right')]},
    {'selector': 'td:nth-child(2)', 'props': [('text-align', 'center')]},
    {'selector': 'td:nth-child(3)', 'props': [('text-align', 'right')]}
])

# 显示结果
print(styled_df)

代码解释

  • 数据收集:user_list负责存储所有抓取到的用户字典,确保数据不丢失。
  • 去重逻辑:利用集合seen_unique_ids记录已出现的uniqueId,仅保留每个用户的第一条数据,避免重复条目。
  • 样式设置:通过style方法调整列和单元格的对齐方式,完全匹配你给出的预期表格格式;若不需要样式,直接使用df即可查看基础结构的DataFrame。

内容的提问来源于stack exchange,提问作者Jeremy Zethof

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 01:48:38