[英]Replace part of pandas dataframe column based on the first two letters
我有一個熊貓數據框,我需要根據前兩個字母有條件地更新值。 該模式很簡單,下面的代碼有效,但感覺不像 Pythonic。 我需要將其擴展到其他字母(至少 11-19/AJ),雖然我可以添加額外的行,但我真的很想以正確的方式做到這一點。 下面的現有代碼
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:]
我無法找到解決此問題的方法,但如果有任何幫助或類似問題的鏈接,我將不勝感激。 謝謝你。
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:]
我會嘗試查找字典並使用map
來加快速度。
要查找字典,您可以使用:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.