在pandas数据框中将列表转换为numpy数组 [英] conversion of lists into a numpy array in pandas dataframe
本文介绍了在pandas数据框中将列表转换为numpy数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我们有一个数据框,其中一列的元素是列表(讨论不是关于是否应该这样做).一个简单的示例如下:
We have a dataframe where the elements of one column are lists (the discussion is not about if this should be done or not). A simple example is the following:
df = pd.DataFrame([[12,[123,234,234]], [14,[124,25,235]], [16,[1267,267,2345]]], columns = ['A', 'B'])
获取:
此处的目标是将列 B 转换为一个numpy数组,如下所示:
the goal here to to convert the column B into a numpy array, like the following one:
.
如果我要求熊猫将列转换为数组:
If I ask to pandas convert the column into an array:
df['B'].values
它返回一个列表数组,与上面的列表不同:
it returns an array of list, which is not the same as the one above:
array([list([123, 234, 234]), list([124, 25, 235]),
list([1267, 267, 2345])], dtype=object)
我们如何解决问题?
推荐答案
如果列表的长度始终相同,则创建嵌套列表,然后转换为np.array
:
If always same length of lists is possible create nested lists and then convert to np.array
:
arr = np.array(df['B'].values.tolist())
#alternative
#arr = np.array(df['B'].tolist())
print (arr)
[[ 123 234 234]
[ 124 25 235]
[1267 267 2345]]
这篇关于在pandas数据框中将列表转换为numpy数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文