Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to preserve original indexes in the new dataframe

def answer_eight():
    templist = list()
    for county, region, p15, p14, ste, cty in zip(census_df.CTYNAME,
                                        census_df.REGION,
                                        census_df.POPESTIMATE2015,
                                        census_df.POPESTIMATE2014,
                                        census_df.STNAME,
                                        census_df.CTYNAME):
        # print(county)
        if region == 1 or region == 2:
            if county.startswith('Washington'):
                if p15 > p14:
                    templist.append((ste, cty))
    labels = ['STNAME', 'CTYNAME']
    df = pd.DataFrame.from_records(templist, columns=labels)
    return df

         STNAME            CTYNAME
0          Iowa  Washington County
1     Minnesota  Washington County
2  Pennsylvania  Washington County
3  Rhode Island  Washington County
4     Wisconsin  Washington County

All these CTYNAME has different indexes in the original census_df. How could I transfer them over to the new DF so the answer looks like:

         STNAME            CTYNAME
12          Iowa  Washington County
222     Minnesota  Washington County
400  Pennsylvania  Washington County
2900  Rhode Island  Washington County
2999     Wisconsin  Washington County
like image 798
feedthemachine Avatar asked Dec 06 '25 20:12

feedthemachine


1 Answers

I'd include the index with the other things your are zipping

def answer_eight():
    templist = list()
    index = list()
    zipped = zip(
        census_df.CTYNAME,
        census_df.REGION,
        census_df.POPESTIMATE2015,
        census_df.POPESTIMATE2014,
        census_df.STNAME,
        census_df.CTYNAME,
        census_df.index
    )        
    for county, region, p15, p14, ste, cty, idx in zipped:
        # print(county)
        if region == 1 or region == 2:
            if county.startswith('Washington'):
                if p15 > p14:
                    templist.append((ste, cty))
                    index.append(idx)
    labels = ['STNAME', 'CTYNAME']
    df = pd.DataFrame(templist, index, labels)
    return df.rename_axis(census_df.index.name)
like image 171
piRSquared Avatar answered Dec 08 '25 10:12

piRSquared



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!