假设我有一个名为“ Student.csv”的CSV文件。 CSV文件包含标题“ EmergencyNum”。我已经使用Python将CSV数据加载到了学生表中。我想按以下格式设置“ EmergencyNum”列, 如果紧急电话号码是8位数字,我应该像xx-xxx-xxx一样加载(例如67-890-876) 如果紧急电话号码是9位数字,那么我应该加载xxx-xxx-xxx(例如987-400-314) 我该怎么办?
示例数据框:
EmergencyNum DesiredColumn
67890876 67-890-876
987400314 987-400-314
答案 0 :(得分:3)
f-strings相对较新。它允许您将变量放在{}
中,以将它们直接注入字符串中。
例如
customer_name = "Ashley Williamson"
# print(f"") # F-strings use f, followed by string.
print(f"Hello {customer_name}")
考虑:
emer_number = 987654321 # Your input number
str_e = str(emer_number) # Convert to string, for length, and direct indexing.
if len(str_e) == 8:
print(f"{str_e[0:2]}-{str_e[2:5]}-{str_e[5:]}") # xx-xxx-xxx
elif len(str_e) == 9:
print(f"{str_e[0:3]}-{str_e[3:6]}-{str_e[6:]}") # xxx-xxx-xxx
答案 1 :(得分:0)
df['EmergencyNum'].astype(str).apply(lambda x: x[:2]+'-'+x[2:5]+'-'+x[5:] if len(x) == 8 else x[:3]+'-'+x[3:6]+'-'+x[6:] )
输出
0 67-890-876
1 987-400-314
Name: EmergencyNum, dtype: object
答案 2 :(得分:0)
见下文
def emergency_number_formatter(number):
num_str = str(number)
if len(num_str) == 8:
return num_str[:2] + '-' + num_str[2:5] + '-' + num_str[5:]
elif len(num_str) == 9:
return num_str[:3] + '-' + num_str[3:6] + '-' + num_str[6:]
else:
raise Exception('Unsupported number: {}. Current len is {}'.format(num_str, len(num_str)))
print(emergency_number_formatter(987400314))
print(emergency_number_formatter(67890876))
输出
987-400-314
67-890-876
答案 3 :(得分:0)
您可以使用grouping option工具。在df=pandas.read_csv(....)
之后,EmergencyNum为int64。
然后
df.EmergencyNum.apply(lambda num: format(num,"_").replace("_","-"))
0 67-890-876
1 987-400-314
Name: EmergencyNum, dtype: object
答案 4 :(得分:-1)
1。使用参数python定义功能
def nu_format(n):
return format(int(n[:-1]), ",").replace(",", "-") + n[-1]
nu_format(67890876)
使用上面的代码尝试