根据值的子集更改数据帧中的值

2024-09-25 12:24:01 发布

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

我有一个数据框,其中一些值是空列表,其他值是dict列表。像这样:

0   [{'text': 'Improvement in steam-engine side-va...   []  []  [{'text': '@einen tetes strut ffice. IMPROV...
1   [{'text': 'Gate.', 'language': 'en', 'truncate...   []  []  [{'text': 'No. 645,359. Patented Mar. 13, I900...
2   [{'text': 'Overseaming sewing-machine.', 'lang...   []  []  [{'text': 'No. 64 5,8l5. Patented Mar. 20, I90...

我想将dict列表中的值更改为列表中第一个dict的一个值。 我本想做这样的事情:

df.loc[df!=[]] = df[0]['text']

这显然不起作用


Tags: 数据notextindf列表sidedict
2条回答

因此,考虑到这个玩具数据框:

import pandas as pd

df = pd.DataFrame(
    [
        [
            [{"text": "Improvement ..."}],
            [],
            [],
            [{"text": "@einen tete..."}],
        ],
        [
            [{"text": "Overseaming..."}],
            [],
            [],
            [{"text": "No. 64 5,8l5..."}],
        ],
    ]
)
print(df)
# Outputs
                               0   1   2                              3
0  [{'text': 'Improvement ...'}]  []  []   [{'text': '@einen tete...'}]
1   [{'text': 'Overseaming...'}]  []  []  [{'text': 'No. 64 5,8l5...'}]

您可以这样做:

df = df.applymap(lambda x: x[0]["text"] if x != [] else x)

print(df)
# Ouputs
                 0   1   2                3
0  Improvement ...  []  []   @einen tete...
1   Overseaming...  []  []  No. 64 5,8l5...

或者,您可以像这样迭代和更新值:

for col in df.columns:
    for i in df.index:
        try:
            df.loc[i, col] = df.loc[i, col][0]["text"]
        except IndexError:
            continue

print(df)
# Ouputs
                 0   1   2                3
0  Improvement ...  []  []   @einen tete...
1   Overseaming...  []  []  No. 64 5,8l5...

改进Laurent的优秀答案,使用dataframe功能一行解决问题:

df.applymap(lambda x:x[0]["text"] if x!=[])

相关问题 更多 >