Issue apppending iterrow rows to list

Viewed 47
ind Pin Ar Code Area Name
0 11 DL Delhi
1 12–13 HR Haryana
2 14–15 PB Punjab
3 16 CH Chandigarh
4 17 HP Himachal Pradesh
5 18–19 JK, LA Jammu and Kashmir, Ladakh

I'm attempting to expand this dataframe from a list of pins/pin ranges and their respective locations to a simple list of pins and locations. In order to do that, I'm iterating through a dataframe, directly copying an entry that doesn't have a hyphen and using a for loop to expand any entry that does. As per what I've read online the best practice when looping is to append rows to a list and then convert the list into a dataframe, so I chose to append all rows to a list 'lst'

lst = []
for index, row in pinloc_df.iterrows():
    if '–' not in row.Pin:
        lst.append(row)
    else:
        dash = row['Pin'].index('–')
        rg_start = row['Pin'][0:2]
        rg_end = row['Pin'][(int(dash)+1):(int(dash)+3)]
        for n in range(int(rg_start),(int(rg_end)+1)):
            row['Pin'] = n
            lst.append(row)
newdf = pd.DataFrame(lst, columns=['Pin', 'Area code', 'Area'])
newdf

Unfortunately, this yields:

ind Pin Ar Cod Area
0 11 DL Delhi
1 13 HR Haryana
1 13 HR Haryana
2 15 PB Punjab
2 15 PB Punjab
... ... ... ...

I suspect this has something to do with the indexes, but I'm not sure where to look. Is there a way of doing this that I'm not seeing? Is my approach entirely wrong?

1 Answers

Create column filled by ranges and use DataFrame.explode:

def f(x):
    
    split = x.strip().split('–')
    #weird `-`, for me working chr(150) for sample data
    #split = x.strip().split(chr(150))
    if len(split) == 1:
        return [int(x)]
    else:
        return range(int(split[0]), int(split[1]) + 1)

df['Pin'] = df['Pin'].apply(f)

df = df.explode('Pin')
print (df)
    Pin Ar Code                  Area Name
ind                                       
0    11      DL                      Delhi
1    12      HR                    Haryana
1    13      HR                    Haryana
2    14      PB                     Punjab
2    15      PB                     Punjab
3    16      CH                 Chandigarh
4    17      HP           Himachal Pradesh
5    18  JK, LA  Jammu and Kashmir, Ladakh
5    19  JK, LA  Jammu and Kashmir, Ladakh
Related