将一个列表索引附加到另一个列表不同长度的索引

时间:2021-05-21 03:51:04

标签: pandas dataframe python-3.7

收到此错误:第 341 行,上传中 lst3 = lst1.extend(lst2) AttributeError: 'Index' 对象没有属性 'extend'


{'Date': ['2_April','3_May','1_June','5_July', '3_April', '9_July'],
                    'State': ['BR', 'JH', 'HR', 'JH', 'BR', 'PB'],
                    'Blank': ['nan','nan','nan','nan','nan','nan'],
                    'District' : ['BS', 'GW', 'AM', 'RN', 'PB', 'GR'],
                    'nan': [Sub-dist, 0, 2, 2, 9, 8],
                    'nan': [Month, 1, 1, 2, 3, 4],
                    'nan': [Year, 2, 0, 0, 0, 0],
                    'nan': [Facility,2, 3, 4, 0, 0],
                    }

    # Partial list of headers
    lst1 = df_.columns[:18]

    # converting first row to list and picking elements after 18th column
    lst2 = df_.iloc[1, 18:].to_numpy()

    lst2 = pd.Index(lst2)

    # extending lst to lst2
    lst3 = lst1.extend(lst2)
    print(lst3)

    # After merging two list Indexes above updating column of dataframe
    df_.columns = lst3

2 个答案:

答案 0 :(得分:1)

使用 values 将索引/系列转换为列表,如下所示

lst2 = pd.Index(lst2).values

答案 1 :(得分:1)

    # Partial list of headers
    lst1 = df_.columns[:18].values

    # converting first row to list
    lst2 = df_.iloc[1, 18:].to_numpy()
    lst2 = pd.Index(lst2).values
    import numpy
    lst3 = numpy.concatenate((lst1, lst2))
    print(lst3)
    df_.columns = lst3
    df_ = df_[2:]