Kim*_*m O 5 python arrays numpy dataframe pandas
如何从 DataFrame 中的两列创建结构化数组?我试过这个:
df = pd.DataFrame(data=[[1,2],[10,20]], columns=['a','b'])
df
a b
0 1 2
1 10 20
x = np.array([([val for val in list(df['a'])],
[val for val in list(df['b'])])])
Run Code Online (Sandbox Code Playgroud)
但这给了我这个:
array([[[ 1, 10],
[ 2, 20]]])
Run Code Online (Sandbox Code Playgroud)
但我想要这个:
[(1,2),(10,20)]
Run Code Online (Sandbox Code Playgroud)
谢谢!
有几种方法。与常规 NumPy 数组相比,您可能会遇到性能和功能方面的损失。
您可以pd.DataFrame.to_records与index=False. 从技术上讲,这是一个记录数组,但对于许多目的来说这已经足够了。
res1 = df.to_records(index=False)
print(res1)
rec.array([(1, 2), (10, 20)],
dtype=[('a', '<i8'), ('b', '<i8')])
Run Code Online (Sandbox Code Playgroud)
手动,您可以通过转换为tuple按行构造结构化数组,然后为dtype参数指定元组列表。
s = df.dtypes
res2 = np.array([tuple(x) for x in df.values], dtype=list(zip(s.index, s)))
print(res2)
array([(1, 2), (10, 20)],
dtype=[('a', '<i8'), ('b', '<i8')])
Run Code Online (Sandbox Code Playgroud)
有什么不同?
很少。recarray是ndarray常规 NumPy 数组类型的子类。另一方面,第二个示例中的结构化数组的类型为ndarray。
type(res1) # numpy.recarray
isinstance(res1, np.ndarray) # True
type(res2) # numpy.ndarray
Run Code Online (Sandbox Code Playgroud)
主要区别在于记录数组便于属性查找,而结构化数组将产生AttributeError:
print(res1.a)
array([ 1, 10], dtype=int64)
print(res2.a)
AttributeError: 'numpy.ndarray' object has no attribute 'a'
Run Code Online (Sandbox Code Playgroud)
使用列表理解将嵌套lists 转换为tuples:
print ([tuple(x) for x in df.values.tolist()])
[(1, 2), (10, 20)]
Run Code Online (Sandbox Code Playgroud)
细节:
print (df.values.tolist())
[[1, 2], [10, 20]]
Run Code Online (Sandbox Code Playgroud)
编辑:您可以转换为to_records,然后转换为np.asarray,检查链接:
df = pd.DataFrame(data=[[True, 1,2],[False, 10,20]], columns=['a','b','c'])
print (df)
a b c
0 True 1 2
1 False 10 20
print (np.asarray(df.to_records(index=False)))
[( True, 1, 2) (False, 10, 20)]
Run Code Online (Sandbox Code Playgroud)