基于JSON中的字符串匹配创建新的Pandas列

2024-06-28 20:40:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧:

df =
     SomeText
0    foo foo foo bar
1    bar foo buzz
2    bar bar bar
3    buzz buzz buzz buzzer

还有一个JSON:

json_dict =

{
    "text": [
        {
            "notes": [],
            "code": 1,
            "word": foo,
        },
        {
            "notes": [],
            "code": 2,
            "word": bar,
        },
        {
            "notes": [buzzer],
            "code": 3,
            "word": buzz,
        }
    ]
}

我想解析SomeText列中的文本,并根据JSON中存储的数据向df添加一个新列。如果单词出现在字符串中,请附加代码。如果单词也与注释匹配,请附加相同的代码

df =
     SomeText                Code
0    foo foo foo bar         1, 1, 1, 2
1    bar foo buzz            2, 1, 3
2    bar bar bar             2, 2, 2
3    buzz buzz buzz buzzer   3, 3, 3, 3
4    not in json             -

JSON中不包含的单词无关紧要

我有一些在数据帧之间做这件事的经验,但不使用JSON文件作为引用

任何帮助都将不胜感激


Tags: 数据代码jsondffoobarcode单词
1条回答
网友
1楼 · 发布于 2024-06-28 20:40:09

设置

df = pd.DataFrame({'SomeText': {0: 'foo foo foo bar', 1: 'bar foo buzz', 2: 'bar bar bar', 3: 'buzz buzz buzz buzzer', 4: 'not in json  '}})
dct = {'text': [{'notes': [], 'code': 1, 'word': 'foo'}, {'notes': [], 'code': 2, 'word': 'bar'}, {'notes': ['buzzer'], 'code': 3, 'word': 'buzz'}]}

创建一个字典,将JSON中的单词映射到它们的值:

mapper = {i['word']: i['code'] for i in dct['text']}
# {'foo': 1, 'bar': 2, 'buzz': 3}

使用列表理解:

df['Code'] = [[mapper[i] for i in t.split() if i in mapper] or '-' for t in df.SomeText]

输出:

                SomeText          Code
0        foo foo foo bar  [1, 1, 1, 2]
1           bar foo buzz     [2, 1, 3]
2            bar bar bar     [2, 2, 2]
3  buzz buzz buzz buzzer     [3, 3, 3]
4          not in json               -

要同时使用notes的内容,请使用一个简单的for循环来创建新字典:

mapper = {}
for i in dct['text']:
    mapper.update({j: i['code'] for j in i['notes']})
    mapper.update({i['word']: i['code']})

                SomeText          Code
0        foo foo foo bar  [1, 1, 1, 2]
1           bar foo buzz     [2, 1, 3]
2            bar bar bar     [2, 2, 2]
3  buzz buzz buzz buzzer  [3, 3, 3, 3]
4          not in json               -

相关问题 更多 >