Skip to main content
 首页 » 编程设计

python之如何在新数据框中保留原始索引

2024年10月01日7EasonJim

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 

所有这些 CTYNAME 在原始 census_df 中都有不同的索引。我怎样才能将它们转移到新的 DF,所以答案看起来像:

         STNAME            CTYNAME 
12          Iowa  Washington County 
222     Minnesota  Washington County 
400  Pennsylvania  Washington County 
2900  Rhode Island  Washington County 
2999     Wisconsin  Washington County 

请您参考如下方法:

我会将索引包含在您正在压缩的其他内容中

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)