Skip to main content
 首页 » 编程设计

python之在列中添加值

2024年11月24日7qlqwjy

我有一个数据框 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