gpt4 book ai didi

python - 如何根据条件更改python数据框中的值(即列表)?

转载 作者:行者123 更新时间:2023-12-01 01:21:27 26 4
gpt4 key购买 nike

我有一个包含歌曲信息的数据帧'songDataFrame'。共有三列:“艺术家”、“标题”、“流派”。前两个是字符串,'genres' 包含流派列表。它看起来像这样:

id  artist             title         genres
1 'Sarah Bareilles' 'Opening Up' ['acoustic','pop', 'piano']
2 'Post Malone' 'Stay' ['Hip-Hop', 'rap', 'trap']
3 'Dean Lewis' 'Waves' ['alternative', 'guitar', 'indie']
4 'Billie Eilish' 'Watch' ['indie', 'indie pop', 'pop']
5 'Passenger' 'Let Her Go' ['metal', 'screamo', 'gore']

艺术家“Passenger”的流派是错误的。我想将现有列表更改为 ['indie rock', 'folk rock']。

如果它不是一个列表,但我用一个字符串替换,我就会这样做:

mask = songDataFrame.artist =='Passenger'
songDataFrame.loc[mask, 'genres'] = 'indie folk'

这样就可以正常工作了。当我用['独立摇滚','民间摇滚']代替'独立民谣'时,

mask = songDataFrame.artist =='Passenger'
songDataFrame.loc[mask, 'genres'] = ['indie folk','folk rock']

我收到此错误:

ValueError: Must have equal len keys and value when setting with an iterable

有办法解决吗?

最佳答案

使用两行并使用loc分配一个字符串,将所有列值设置为字符串,然后将它们返回到列表:

import ast
songDataFrame.loc[songDataFrame['artist']=='Passenger','genres']="['indie folk','folk rock']"
songDataFrame['genres']=songDataFrame['genres'].astype(str).apply(ast.literal_eval)

现在:

print(songDataFrame)

是:

   id           artist       title                        genres
0 1 Sarah Bareilles Opening Up [acoustic, pop, piano]
1 2 Post Malone Stay [Hip-Hop, rap, trap]
2 3 Dean Lewis Waves [alternative, guitar, indie]
3 4 Billie Eilish Watch [indie, indie pop, pop]
4 5 Passenger Let Her Go [indie folk, folk rock]

关于python - 如何根据条件更改python数据框中的值(即列表)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53801179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com