Create and set an element of a Pandas DataFrame to a list

后端 未结 3 1599
野的像风
野的像风 2021-01-13 01:14

I have a Pandas DataFrame that I\'m creating row-by-row (I know, I know, it\'s not Pandorable/Pythonic..). I\'m creating elements using .loc like so



        
3条回答
  •  悲哀的现实
    2021-01-13 02:13

    You can use pd.at instead:

    df = pd.DataFrame()
    df['B'] = [1, 2, 3]
    df['A'] = None
    df.at[1, 'A'] = np.array([1, 2, 3])
    

    When you use pd.loc, pandas thinks you are interacting with a set of rows. So if you try to assign an array using pd.loc, pandas will try to match each element of an array with a corresponding element accessed by pd.loc, hence the error.

提交回复
热议问题