ValueError: setting an array element with a sequence. for Pandas

后端 未结 1 415
醉梦人生
醉梦人生 2021-02-05 12:53

I have a Pandas dataframe, called output. The basic issue is that I would like to set a certain row, column in the dataframe

相关标签:
1条回答
  • 2021-02-05 13:09

    If you really want to set a list as the value for the element, the issue is with the dtype of the column, when you create the DataFrame, the dtype gets inferred as float64 , since it only contains numeric values.

    Then when you try to set a list as the value, it errors out, due to the dtype . A way to fix this would be to use a non-numeric dtype (like object) or so. Example -

    output['Sold Count'] = output['Sold Count'].astype(object)
    output.loc['Project1','Sold Count'] = [1000.0,800.0] #Your list
    

    Demo -

    In [91]: output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1'])
    
    In [92]: output
    Out[92]:
              Sold Count
    Project1         800
    
    In [93]: output['Sold Count'] = output['Sold Count'].astype(object)
    
    In [94]: output.loc['Project1','Sold Count'] = [1000.0,800.0]
    
    In [95]: output
    Out[95]:
                   Sold Count
    Project1  [1000.0, 800.0]
    

    You can also specify the dtype while creating the DataFrame, Example -

    output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1'],dtype=object)
    output.loc['Project1','Sold Count'] = [1000.0,800.0]
    

    Demo -

    In [96]: output = pd.DataFrame(data = [[800.0]], columns=['Sold Count'], index=['Project1'],dtype=object)
    
    In [97]: output.loc['Project1','Sold Count'] = [1000.0,800.0]
    
    In [98]: output
    Out[98]:
                   Sold Count
    Project1  [1000.0, 800.0]
    
    0 讨论(0)
提交回复
热议问题