gpt4 book ai didi

python - 在列中添加值

转载 作者:太空宇宙 更新时间:2023-11-04 04:07:43 25 4
gpt4 key购买 nike

我有一个数据框 df,我想在 cast 和 genres 列中添加 '/'这样每个单元格包含3个'/'

id  movie      cast      genres  runtime
1 Furious a/b/c/d a/b 23
2 Minions a/b/c a/b/c 55
3 Mission a/b a 67
4 Kingsman a/b/c/d a/b/c/d 23
5 Star Wars a a/b/c 45

所以,它的输出看起来像这样

id  movie      cast      genres  runtime
1 Furious a/b/c/d a/b// 23
2 Minions a/b/c/ a/b/c/ 55
3 Mission a/b// a/// 67
4 Kingsman a/b/c/d a/b/c/d 23
5 Star Wars a/// a/b/c/ 45

最佳答案

这是定义自定义函数的一种方法:

def add_values(df, *cols):
for col in cols:
# amount of "/" to add at each row
c = df[col].str.count('/').rsub(3)
# translate the above to as many "/" as required
ap = [i * '/' for i in c.tolist()]
# Add the above to the corresponding column
df[col] = [i + j for i,j in zip(df[col], ap)]
return df

add_values(df, 'cast', 'genres')

id movie cast genres runtime
0 1 Furious a/b/c/d a/b// 23
1 2 Minions a/b/c/ a/b/c/ 55
2 3 Mission a/b// a/// 67
3 4 Kingsman a/b/c/d a/b/c/d 23
4 5 StarWars a/// a/b/c/ 45

关于python - 在列中添加值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56935588/

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