python - 如何从列中提取字符串的某些部分以在 Pandas 中创建其他列

标签 python pandas dataframe

我有一个看起来像这样的数据框

<表类=“s-表”> <标题> 标题 评分 <正文> 学校会扼杀创造力吗? [{'id': 7, 'name': '有趣', 'count': 19645}, {'id': 1, 'name': '美丽', 'count': 4573}, {' id': 9, 'name': '聪明', 'count': 6073}, {'id': 3, 'name': '勇敢', 'count': 3253}, {'id': 11, ' name': '长篇大论', 'count': 387}, {'id': 2, 'name': '令人困惑', 'count': 242}, {'id': 8, 'name': '信息丰富' , 'count': 7346}, {'id': 22, 'name': '迷人', 'count': 10581}, {'id': 21, 'name': '不令人信服', 'count': 300 }, {'id': 24, 'name': '有说服力', 'count': 10704}, {'id': 23, 'name': '令人瞠目结舌', 'count': 4439}, {' id':25,'名称':'好的','计数':1174},{'id':26,'名称':'讨厌','计数':209},{'id':10,' name': '鼓舞人心', 'count': 24924}] 简单的设计可以挽救生命 [{'id': 9, 'name': '聪明', 'count': 269}, {'id': 3, 'name': '勇敢', 'count': 92}, {' id': 7, 'name': '有趣', 'count': 131}, {'id': 2, 'name': '令人困惑', 'count': 42}, {'id': 1, ' name': '美丽', 'count': 91}, {'id': 8, 'name': '信息丰富', 'count': 446}, {'id': 10, 'name': '鼓舞人心' , 'count': 397}, {'id': 22, 'name': '迷人', 'count': 515}, {'id': 11, 'name': '长篇大论', 'count': 45 }, {'id': 21, 'name': '没有说服力', 'count': 49}, {'id': 24, 'name': '有说服力', 'count': 1234}, {'id' : 25, 'name': '好的', 'count': 73}, {'id': 23, 'name': '令人瞠目结舌', 'count': 139}, {'id': 26, ' name': '令人讨厌', 'count': 21}]

我想解析评级中的数据,使其看起来像

<表类=“s-表”> <标题> 标题 评分 计数 <正文> 学校会扼杀创造力吗? 有趣 19645 学校会扼杀创造力吗? 美丽 4573

我尝试使用 } 作为分隔符来分解数据

#explode ratings by title
df['ratings'] = df['ratings'].str.split('}')
df_explode_ratings = df.explode('ratings').reset_index(drop=True)
cols = list(df_explode_ratings.columns)
cols.append(cols.pop(cols.index('title')))
df_explode_ratings = df_explode_ratings[cols]
df_explode_cols = ['title', 'ratings']
df_explode_ratings = df_explode_ratings.drop(columns=[col for col in df_explode_ratings if col not in df_explode_cols])

这可行,但我仍然需要进一步解析它,我打算在 上再次拆分,但最终在评级列中得到 NaN 值。

最佳答案

您的列“Ratings”是字符串还是字典列表?如果是字符串,您可以应用 ast.literal_eval 然后分解列(如果是字典列表,您可以省略 literal_eval 步骤):

from ast import literal_eval

df.Ratings = df.Ratings.apply(literal_eval)
df = df.explode("Ratings")
df["Rating"] = df.apply(lambda x: x["Ratings"]["name"], axis=1)
df["Count"] = df.apply(lambda x: x["Ratings"]["count"], axis=1)
df = df.drop(columns="Ratings")
print(df)

打印:

                           Title        Rating  Count
0    Do schools kill creativity?         Funny  19645
0    Do schools kill creativity?     Beautiful   4573
0    Do schools kill creativity?     Ingenious   6073
0    Do schools kill creativity?    Courageous   3253
0    Do schools kill creativity?    Longwinded    387
0    Do schools kill creativity?     Confusing    242
0    Do schools kill creativity?   Informative   7346
0    Do schools kill creativity?   Fascinating  10581
0    Do schools kill creativity?  Unconvincing    300
0    Do schools kill creativity?    Persuasive  10704
0    Do schools kill creativity?  Jaw-dropping   4439
0    Do schools kill creativity?            OK   1174
0    Do schools kill creativity?     Obnoxious    209
0    Do schools kill creativity?     Inspiring  24924
1  Simple designs to save a life     Ingenious    269
1  Simple designs to save a life    Courageous     92
1  Simple designs to save a life         Funny    131
1  Simple designs to save a life     Confusing     42
1  Simple designs to save a life     Beautiful     91
1  Simple designs to save a life   Informative    446
1  Simple designs to save a life     Inspiring    397
1  Simple designs to save a life   Fascinating    515
1  Simple designs to save a life    Longwinded     45
1  Simple designs to save a life  Unconvincing     49
1  Simple designs to save a life    Persuasive   1234
1  Simple designs to save a life            OK     73
1  Simple designs to save a life  Jaw-dropping    139
1  Simple designs to save a life     Obnoxious     21

但正如评论中所建议的,更好的是在创建 DataFrame 之前处理/解析数据。

关于python - 如何从列中提取字符串的某些部分以在 Pandas 中创建其他列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67115140/

相关文章:

python-3.x - 从元数据动态创建 DataFrame 列

python - 在特定子字符串上拆分字符串并保留它

python - Panda AssertionError 列已传递,传递的数据有 2 列

python - 使用惯用的 Python 删除 pandas 列中的空格和换行符?

python - 连接变量和字符串Python脚本

Python - 对 pandas 数据框中的两行应用 concat 函数

python - 在 Pandas python 中聚合数据

python - Tensorflow:ValueError:在单次检测中为 None 时无法加载 save_path

python - 为什么 Python 用于 Web 开发?

python - 如何在标签中的 tkinter 上制作字幕?