繁体   English   中英

根据预先存在的列在 pandas 中创建另一列

[英]Creating another column in pandas based on a pre-existing column

我的数据框中有第三列,我希望能够创建看起来几乎相同的第四列,除了它没有双引号并且列表中的每个 ID 之前都有一个“用户/”前缀。 此外,有时它只是一个 ID 与 ID 列表(如示例 DF 所示)。

原来的

col1   col2     col3 
01      01     "ID278, ID289"

02      02     "ID275"

想要的

col1   col2     col3                col4
01      01     "ID278, ID289"     user/ID278, user/ID289

02      02     "ID275"            user/ID275

鉴于:

   col1  col2            col3
0   1.0   1.0  "ID278, ID289"
1   2.0   2.0         "ID275"
2   2.0   1.0             NaN

正在做:

df['col4'] = (df.col3.str.strip('"')  # Remove " from both ends.
                     .str.split(', ') # Split into lists on ', '.
                     .apply(lambda x: ['user/' + i for i in x if i] # Apply this list comprehension,
                                       if isinstance(x, list)  # If it's a list.
                                       else x)
                     .str.join(', ')) # Join them back together.
print(df)

输出:

   col1  col2            col3                    col4
0   1.0   1.0  "ID278, ID289"  user/ID278, user/ID289
1   2.0   2.0         "ID275"              user/ID275
2   2.0   1.0             NaN                     NaN
df.col4 = df.col3.str.strip('"')
df.col4 = 'user/' + df.col4

应该做的伎俩。

通常,向量化字符串操作的操作由pd.Series.str...操作执行。 它们的大多数名称都与 Python 字符串方法或re方法非常匹配。 Pandas 通常支持带有字符串的标准 Python 运算符(+、-、* 等),并将标量作为向量与您正在使用的列的维度进行插值。

一个缓慢的选择总是只使用Series.apply(func) ,它只是迭代系列中的值并将值传递给函数func

您可以使用 .apply() 功能:

def function(x):
    if not x:
        return ""
    
    elements = x.split(", ")
    out = list()
    
    for i in elements:
        out.append(f"user/{i}")
        
    return ", ".join(out)

df["col4"] = df.col3.apply(function)

返回:

col1  col2  col3          col4
1     1     ID278, ID289  user/ID278, user/ID289
2     2     ID275         user/ID275
3     3 

这是一个同时考虑双引号和 ID 列表的解决方案:

# remove the double quotes
df['col4'] = df['col3'].str.strip('"')
# split the string, add prefix user/, and then join
df['col4'] = df['col4'].apply(lambda x: ', '.join(f"user/{userId}" for userId in x.split(', ')))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM