简体   繁体   English

将 pandas dataframe 中的列表 object 转换为 Z2EA9510C37F7F89E4941FF75F62F21 数组

[英]Convert List object in a pandas dataframe to numpy array

One of my pandas dataframe column is a list object of m columns, each row looks like this 'List(0.42, 0.24, 0.78,...)' with a list of n elements wrapped by quote marks.我的 pandas dataframe 列之一是 m 列的列表 object ,每一行看起来像这样'List(0.42, 0.24, 0.78,...)' Dtype for this column is Object.此列的 Dtype 为 Object。

I need to convert this column into am X n np array.我需要将此列转换为 am X n np 数组。 So far I tried applying np.fromstring(col content) but it's mostly returning 'ValueError: string size must be a multiple of element size'.到目前为止,我尝试应用 np.fromstring(col content) 但它主要返回“ValueError:字符串大小必须是元素大小的倍数”。 It did work for the first row though.不过,它确实适用于第一行。

How to appropriately convert this List object column to an array?如何将此列表 object 列正确转换为数组?

We need trim your string, then split我们需要修剪你的字符串,然后split

np.array(s.str.strip('List').str.strip('(|)').str.split(', ').tolist())
Out[11]: 
array([['0.42', '0,24', '0.78,...'],
       ['0.42', '0,24', '0.78,...']], dtype='<U8')

Updated更新

s.str.strip('List').str.strip('(|)').str.split(',',expand=True).apply(lambda x : x.str.strip()).values
Out[18]: 
array([['0.42', '0', '24', '0.78', '...'],
       ['0.42', '0', '24', '0.78', '...']], dtype=object)

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

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