Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)
my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]
print(type(my_list),type(my_dt),type(new_list))
tolist() works fine even if encountered a nested array, say a pandas DataFrame;
my_list = [0,1,2,3,4,5,4,3,2,1,0]
my_dt = pd.DataFrame(my_list)
new_list = [i[0] for i in my_dt.values.tolist()]
print(type(my_list),type(my_dt),type(new_list))
发布评论
评论(6)
使用
tolist()
:请注意,这会将值从它们可能具有的任何 numpy 类型(例如 np.int32 或 np.float32)转换为“最接近的兼容 Python 类型”(在列表中)。如果你想保留 numpy 数据类型,你可以在数组上调用 list() ,你最终会得到一个列表 numpy 标量。 (感谢 Mr_and_Mrs_D 在评论中指出这一点。)
Use
tolist()
:Note that this converts the values from whatever numpy type they may have (e.g. np.int32 or np.float32) to the "nearest compatible Python type" (in a list). If you want to preserve the numpy data types, you could call list() on your array instead, and you'll end up with a list of numpy scalars. (Thanks to Mr_and_Mrs_D for pointing that out in a comment.)
如果 numpy 数组形状是二维的,则 numpy .tolist 方法会生成嵌套列表。
如果需要平面列表,可以使用下面的方法。
The numpy .tolist method produces nested lists if the numpy array shape is 2D.
if flat lists are desired, the method below works.
即使遇到嵌套数组,例如 pandas DataFrame,
tolist()
也能正常工作;tolist()
works fine even if encountered a nested array, say a pandasDataFrame
;另一种选择
也有效。
Another option
also works.
将数组转换为列表的最简单方法是使用 numpy 包:
要检查数据类型,可以使用以下命令:
The easiest way to convert array to a list is using the numpy package:
To check the data type, you can use the following: