我希望将特定的整数列格式化为ssn格式(xxx-xx-xxxx)。我看到openpyxl有内置风格。我一直在使用熊猫,我不确定它是否能做到这种特定的格式。
我确实看到了-
df.iloc[:,:].str.replace(',', '')但我想用-代替“,”。
import pandas as pd
df = pd.read_excel('C:/Python/Python37/Files/Original.xls')
df.drop(['StartDate', 'EndDate','EmployeeID'], axis = 1, inplace=True)
df.rename(columns={'CheckNumber': 'W/E Date', 'CheckBranch': 'Branch','DeductionAmount':'Amount'},inplace=True)
df = df[['Branch','Deduction','CheckDate','W/E Date','SSN','LastName','FirstName','Amount','Agency','CaseNumber']]
ssn = (df['SSN'] # the integer column
.astype(str) # cast integers to string
.str.zfill(8) # zero-padding
.pipe(lambda s: s.str[:2] + '-' + s.str[2:4] + '-' + s.str[4:]))
writer = pd.ExcelWriter('C:/Python/Python37/Files/Deductions Report.xlsx')
df.to_excel(writer,'Sheet1')
writer.save()发布于 2018-11-26 17:36:45
你的问题有点让人困惑,看看这是否有帮助:
如果您有一个整数列,并且您希望创建一个由字符串组成的新列,那么将以SSN (社会保险号码)格式。你可以尝试这样的方法:
df['SSN'] = (df['SSN'] # the "integer" column
.astype(int) # the integer column
.astype(str) # cast integers to string
.str.zfill(9) # zero-padding
.pipe(lambda s: s.str[:3] + '-' + s.str[3:5] + '-' + s.str[5:]))发布于 2018-11-26 17:47:53
设置
社会保险号码是使用表格:AAA-GG-SSSS的九位数字。
s = pd.Series([111223333, 222334444])
0 111223333
1 222334444
dtype: int64选项1
使用zip和numpy.unravel_index
pd.Series([
'{}-{}-{}'.format(*el)
for el in zip(*np.unravel_index(s, (1000,100,10000)))
])选项2
使用f-strings
pd.Series([f'{i[:3]}-{i[3:5]}-{i[5:]}' for i in s.astype(str)])
这两种产品都有:
0 111-22-3333
1 222-33-4444
dtype: objecthttps://stackoverflow.com/questions/53486141
复制相似问题