我有一个处理多个文件的python程序。每个文件都有基于部门的客户id列。有些文件有8位客户id,有些文件有9位客户id。 我需要这样做
if length of customer id column value is == 8:
input_file['customer_id'] = input_file['customer_id'].str[0:2] + '-' + input_file['customer_id'].str[2:8]
if length of customer id column value is == 9:
input_file['customer_id'] = 'K' + '-' + input_file['customer_id'].str[0:3] + '-' + input_file['customer_id'].str[3:8]
输入
id cusotmerid
1 89898988
2 898989889
输出
id cusotmerid
1 89-898988
2 K-898-989889
我怎样才能做到这一点。找不到任何可以执行此操作的内容
您可以使用
np.select
。为了检查字符串的长度,必须首先确保列的格式是字符串,因此.astype(str)
。然后,您可以使用.apply(lambda x: len(x) == condition)
根据条件返回结果:将
np.select
语句分解为条件和结果可能更容易。我传递的3个参数是条件、结果和默认值(如果不满足任何条件)你也可以这样做
您可以使用
pd.Series.map
和内置的len
查找列值的长度。有了它,您可以确定如何分配值使用
astype(str)
将数值转换为字符串,以便进行字符串连接这应该是新值赋值的一部分
其输出为:
相关问题 更多 >
编程相关推荐