Python 根据前两个字母替换数据框列的一部分
我有一个pandas数据框,需要根据前两个字母有条件地更新值。模式很简单,下面的代码也可以工作,但它感觉不到pythonic。我需要将它扩展到其他字母(至少11-19/A-J),虽然我可以添加额外的行,但我真的希望用正确的方法来做。现有代码如下Python 根据前两个字母替换数据框列的一部分,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个pandas数据框,需要根据前两个字母有条件地更新值。模式很简单,下面的代码也可以工作,但它感觉不到pythonic。我需要将它扩展到其他字母(至少11-19/A-J),虽然我可以添加额外的行,但我真的希望用正确的方法来做。现有代码如下 df['REFERENCE_ID'] = df['PRECERT_ID'].astype(str) df.loc[df['REFERENCE_ID'].str.startswith('11'), 'REFERENCE_ID'] = 'A' + df['P
df['REFERENCE_ID'] = df['PRECERT_ID'].astype(str)
df.loc[df['REFERENCE_ID'].str.startswith('11'), 'REFERENCE_ID'] = 'A' + df['PRECERT_ID'].str[-7:]
df.loc[df['REFERENCE_ID'].str.startswith('12'), 'REFERENCE_ID'] = 'B' + df['PRECERT_ID'].str[-7:]
df.loc[df['REFERENCE_ID'].str.startswith('13'), 'REFERENCE_ID'] = 'C' + df['PRECERT_ID'].str[-7:]
df.loc[df['REFERENCE_ID'].str.startswith('14'), 'REFERENCE_ID'] = 'D' + df['PRECERT_ID'].str[-7:]
df.loc[df['REFERENCE_ID'].str.startswith('15'), 'REFERENCE_ID'] = 'E' + df['PRECERT_ID'].str[-7:]
我想我可以用一个字母列表,比如
letters = list(string.ascii_uppercase)
但我对数据帧(以及一般的python)还不熟悉,无法理解获得与之等效的数据帧的语法
letters = list(string.ascii_uppercase)
text = '1523456789'
first = int(text[:2])
text = letters[first-11] + text[-7:]
我无法找到解决这个问题的方法,但如果有任何帮助或类似问题的链接,我将不胜感激。谢谢。我会尝试制作一个查找字典,并使用
map
来加快速度
df['REFERENCE_ID'] = df['PRECERT_ID'].astype(str)
# Save all uppercase english letters in a list
letters = list(string.ascii_uppercase)
# Enumerate over the letters list and start with 11 as the OP wants in this way only.
# All the uppercase english letters and corresponding numbers starting with 11.
for i,l in enumerate(letters, start=11):
df.loc[df['REFERENCE_ID'].str.startswith(str(i)), 'REFERENCE_ID'] = l + df['PRECERT_ID'].str[-7:]
要使查找命令成为命令,您可以使用:
lu_dict = dict(zip([str(i) for i in range(11,20)],[chr(i) for i in range(65,74)]))
返回:
{'11': 'A',
'12': 'B',
'13': 'C',
'14': 'D',
'15': 'E',
'16': 'F',
'17': 'G',
'18': 'H',
'19': 'I'}
然后可以使用.str.slice.map
来避免for循环
df = pd.DataFrame(data = {'Reference_ID':['112326345','12223356354','6735435634']})
df.Reference_ID = df.Reference_ID.astype(str)
df.loc[:,'Reference_new'] = df.Reference_ID.str.slice(0,2).map(lu_dict) + df.Reference_ID.str.slice(-7, )
其结果是:
Reference_ID Reference_new
0 112326345 A2326345
1 12223356354 B3356354
2 6735435634 NaN
虽然这段代码可以解决这个问题,但如何以及为什么解决这个问题将真正有助于提高您的帖子质量,并可能导致更多的投票。请记住,你是在将来回答读者的问题,而不仅仅是现在提问的人。请在回答中添加解释,并说明适用的限制和假设。