Creating dataframe from a dictionary where entries have different lengths

前端 未结 9 1605
生来不讨喜
生来不讨喜 2020-11-22 14:04

Say I have a dictionary with 10 key-value pairs. Each entry holds a numpy array. However, the length of the array is not the same for all of them.

How can I create a

9条回答
  •  悲哀的现实
    2020-11-22 14:44

    If you don't want it to show NaN and you have two particular lengths, adding a 'space' in each remaining cell would also work.

    import pandas
    
    long = [6, 4, 7, 3]
    short = [5, 6]
    
    for n in range(len(long) - len(short)):
        short.append(' ')
    
    df = pd.DataFrame({'A':long, 'B':short}]
    # Make sure Excel file exists in the working directory
    datatoexcel = pd.ExcelWriter('example1.xlsx',engine = 'xlsxwriter')
    df.to_excel(datatoexcel,sheet_name = 'Sheet1')
    datatoexcel.save()
    
       A  B
    0  6  5
    1  4  6
    2  7   
    3  3   
    

    If you have more than 2 lengths of entries, it is advisable to make a function which uses a similar method.

提交回复
热议问题