如何在新的datafram中保留原始索引

2024-09-28 22:22:10 发布

您现在位置:Python中文网/ 问答频道 /正文

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在最初的人口普查中都有不同的索引。我怎样才能把他们转移到新的国防部,这样答案看起来像:

^{pr2}$

Tags: dflabelsifregioncensuscountyctyste
2条回答

在开始筛选之前,可以将原始索引分配给具有以下条件的列:

census_df['original index'] = census_df.index

然后把它当作你要选择的其他专栏之一。在

我会把索引和其他你正在压缩的东西一起

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)

相关问题 更多 >