简体   繁体   English

如何在 Pandas 中将带有数字列表的列转换为 np.array 格式

[英]How to convert a column with list of numbers to np.array format in Pandas

How to convert all rows of a column to numpy array format in a pandas dataframe?如何将列的所有行转换为 pandas dataframe 中的 numpy 数组格式? A sample dataframe:样品 dataframe: 在此处输入图像描述

df=pd.DataFrame({
        "actual":["1,0,0,1","0,0,1,0"],
        "predicted":["[1,0,0,0]","[0,1,1,1]"]
    })

Ideal data frame:理想数据框:

在此处输入图像描述

I tried to convert the actual column to array format using the code below but failed.我尝试使用下面的代码将actual列转换为数组格式,但失败了。

df['actual']=df.actual(lambda x: np.array([int(s) for s in x.to_numpy().split(',')]))

在此处输入图像描述

The error comes because of df.actual( you call on the column itself, like df['actual']( , you may use Series.apply and to_numpy doesn't exists on a str错误是因为df.actual(你调用列本身,比如df['actual']( ,你可以使用Series.apply并且to_numpystr上不存在

df['actual'] = df.actual.apply(lambda x: np.array([int(s) for s in x.split(',')]))

         actual  predicted
0  [1, 0, 0, 1]  [1,0,0,0]
1  [0, 0, 1, 0]  [0,1,1,1]

You are missing the 'apply' function in the series.您缺少该系列中的“应用” function。 And you don't have to call .to_numpy()而且您不必调用.to_numpy()

df['actual']=df.actual.apply(lambda x: np.array([int(s) for s in x.split(',')]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM