gpt4 book ai didi

python - Pandas 数据帧 : How to extract the last two string type numbers from a column which doesn't always end with the two numbers

转载 作者:行者123 更新时间:2023-11-28 21:35:08 24 4
gpt4 key购买 nike

对于标题可能造成的混淆,我深表歉意,这是我正在尝试做的事情:

我正在尝试将我的地 block 数据框与我的市政代码查找表合并。包裹数据框:

df1.head()

PARID OWNER1
0 B10 2 1 0131 WILSON ROBERT JR
1 B10 2 18B 0131 COMUNALE MICHAEL J & MARY ANN
2 B10 2 18D 0131 COMUNALE MICHAEL J & MARY ANN
3 B10 2 19F 0131 MONROE & JEFFERSON HOLDINGS LLC
4 B10 4 11 0131 NOEL JAMES H

市政代码数据框:

df_LU.head()
PARID Municipality
0 01 Allen Twp.
1 02 Bangor
2 03 Bath
3 04 Bethlehem
4 05 Bethlehem Twp.

df1 第一列中的最后两个数字(“B10 2 1 0131”中的“31”)是我需要与市政代码 DataFrame 合并的市政代码。但是在我的30000多条记录中,大约有200条记录以如下所示的字母结尾:

        PARID           OWNER1  
299 D11 10 10 0131F HOWARD THEODORE P & CLAUDIA S
1007 F10 4 3 0134F KNEEBONE JUDY ANN
1011 F10 5 2 0134F KNEEBONE JUDY ANN
1114 F8 18 10 0626F KNITTER WILBERT D JR & AMY J
1115 F8 18 8 0626F KNITTER DONALD

对于这些行,最后一个字母之前的两个数字是我需要提取的代码(如“D11 10 10 0131F”中的“31”)

如果我只是使用 pd.DataFrame(df1['PARID'].str[-2:])这将给我:

PARID
...
299 1F
...

虽然我需要的是:

PARID
...
299 31
...

我完成这个的代码非常冗长,其中几乎包括:

  1. 连接所有以 2 个数字结尾的行。
  2. 找出“PARID”字段中以字母结尾的行的索引
  3. 再次将第 2 步的结果与市政府查询数据框结合起来。

代码在那里:

#Do the extraction and merge for the rows that end with numbers
df_2015= df1[['PARID','OWNER1']]
df_2015['PARID'] = df_2015['PARID'].str[-2:]
df_15r =pd.merge(df_2015, df_LU, how = 'left', on = 'PARID')
df_15r

#The pivot result for rows generated from above.
Result15_First = df_15r.groupby('Municipality').count()
Result15_First.to_clipboard()

#Check the ID field for rows that end with letters
check15 = df_2015['PARID'].unique()
check15
C = pd.DataFrame({'ID':check15})
NC = C.dropna()
LNC = NC[NC['ID'].str.endswith('F')]
MNC = NC[NC['ID'].str.endswith('A')]
F = [LNC, MNC]
NNC = pd.concat(F, axis = 0)


s = NNC['ID'].tolist()
s

# Identify the records in s

df_p15 = df_2015.loc[df_2015['PARID'].isin(s)]
df_p15

# Separate out a dataframe with just the rows that end with a letter
df15= df1[['PARID','OWNER1']]
df15c = df15[df15.index.isin(df_p15.index)]
df15c

#This step is to create the look up field from the new data frame, the two numbers before the ending letter.
df15c['PARID1'] = df15c['PARID'].str[-3:-1]
df15c

#Then I will join the look up table
df_15t =df15c.merge(df_LU.set_index('PARID'), left_on = 'PARID1', right_index = True)

df_15b = df_15t.groupby('Municipality').count()
df_15b

直到我完成后,我才意识到我的代码对于一个看似简单的任务来说是多么冗长。如果有更好的实现方式,这是肯定的,请告诉我。谢谢。

最佳答案

您可以使用 pandas 字符串方法来提取最后两个数字

df1['PARID'].str.extract('.*(\d{2})', expand = False)

你得到

0    31
1 31
2 13
3 13
4 31

关于python - Pandas 数据帧 : How to extract the last two string type numbers from a column which doesn't always end with the two numbers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52601707/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com