如何在新数据帧中保留原始索引

时间:2017-05-05 07:00:41

标签: python pandas 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

所有这些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

1 个答案:

答案 0 :(得分:1)

在开始过滤之前,您可以使用以下内容将原始索引分配给列:

public class ExpanderDataGrid : DataGrid
    {
        public string SelectedExpanderName
        {
            get
            {
                return (string)GetValue(SelectedExpanderNameProperty);
            }
            set
            {
                SetValue(SelectedExpanderNameProperty, value);
            }
        }

        public static readonly DependencyProperty SelectedExpanderNameProperty = DependencyProperty.Register("SelectedExpanderName",
                typeof(string), typeof(ExpanderDataGrid),
            new FrameworkPropertyMetadata("",
            FrameworkPropertyMetadataOptions.BindsTwoWayByDefault));
    }

然后将其视为您选择的其他列之一。