无法使用python将数据帧中的列表传输到numpy数组
对于数据帧无法使用python将数据帧中的列表传输到numpy数组,python,pandas,numpy,Python,Pandas,Numpy,对于数据帧df: name list1 list2 a [1, 3, 10, 12, 20..] [2, 6, 23, 29...] b [2, 10, 14, 3] [4, 7, 8, 13...] c [] [98, 101, 200] ... 我想将list1和list2传输到np.array,然后hstack它们
df
:
name list1 list2
a [1, 3, 10, 12, 20..] [2, 6, 23, 29...]
b [2, 10, 14, 3] [4, 7, 8, 13...]
c [] [98, 101, 200]
...
我想将list1
和list2
传输到np.array
,然后hstack
它们。以下是我所做的:
df.pv = df.apply(lambda row: np.hstack((np.asarray(row.list1), np.asarray(row.list2))), axis=1)
我犯了这样一个错误:
ValueError: Shape of passed values is (138493, 175), indices imply (138493, 4)
其中138493==len(df)
请注意,list1
和list2
中的某些值是空列表,[]
。并且列表的长度在行之间是不同的。你知道原因是什么吗?我怎样才能解决这个问题?提前谢谢
编辑:
当我尝试将一个列表转换为数组时:
df.apply(lambda row: np.asarray(row.list1), axis=1)
也会发生以下错误:
ValueError: Empty data passed with indices specified.
您的apply函数几乎是正确的。您所要做的就是将np.hstack()
函数的输出转换回python列表
df.apply(lambda row: list(np.hstack((np.asarray(row.list1), np.asarray(row.list2)))), axis=1)
代码如下所示(包括df创建):
输出:
0 [1, 3, 10, 12, 20, 2, 6, 23, 29]
1 [2.0, 10.0, 1.4, 3.0, 4.0, 7.0, 8.0, 13.0]
2 [98.0, 101.0, 200.0]
Name: list3, dtype: object
如果您想要numpy阵列,我唯一能让它工作的方法是:
df['list3'] = df['list3'].apply(lambda x: np.array(x))
print(type(df['list3'].ix[0]))
Out[] : numpy.ndarray
你能提供一个可复制的输入吗?@ColonelBeauvel谢谢你的回复!上面的样本不是可以复制的吗?@user5779223你是如何创建数据帧的,他就是这么说的meant@MMF我读入一个数据集并将其转换为如下形式。事实上,我仍然不知道您需要什么信息?请与我们分享您创建
df
的代码df=?
谢谢你的回答,但是如果我想要一个numpy数组呢?
df['list3'] = df['list3'].apply(lambda x: np.array(x))
print(type(df['list3'].ix[0]))
Out[] : numpy.ndarray