我有一列应该包含以下格式的数据:
xxxx-xxx
但我发现某些记录缺少连字符,因此我需要更新这些记录的数据。我看到的数据格式如下:
xxxx-xxx(用于少量记录) xxxxxxx(剩余记录)
对于xxxxxxx格式的记录,我需要更新数据并在第6个位置插入连字符(-)以将其转换为预期格式(xxxx-xxx)。
我的逻辑: 我正在尝试过滤长度不为 8 且不包含连字符 (-) 的记录,然后在第六位插入连字符。
我尝试过的代码(但它给出了错误):
if df.col.str.len()!=9 and '-' not in df['col']:
df['col']=df['col'].str[:5] +'-' + df['col'].str[5:]
有没有更简单的方法来完成这个?
用
apply(lambda ...)
完成它
# Using a lambda function
df['col'] = df['col'].apply(lambda x: x[:5] + '-' + x[5:]
if len(x) != 9 and '-' not in x else x)