回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>如何将pandas<code>DataFrame</code>转换为以下具有列名的Numpy数组</p>
<pre><code>array([('Heidi Mitchell', 'uboyd@hotmail.com', 74, 52, 'female', '1121', 'cancer', '03/06/2018'),
('Kimberly Kent', 'wilsoncarla@mitchell-gree', 63, 51, 'male', '2003', 'cancer', '16/06/2017')],
dtype=[('name', '<U16'), ('email', '<U25'), ('age', '<i4'), ('weight', '<i4'), ('gender', '<U10'), ('zipcode', '<U6'), ('diagnosis', '<U6'), ('dob', '<U16')])
</code></pre>
<p>这是我的熊猫数据帧<code>df</code>:</p>
<pre><code>col1 col2
3 5
3 1
4 5
1 5
2 2
</code></pre>
<p>我尝试将其转换为以下内容:</p>
<pre><code>import numpy as np
dt = np.dtype([('col1', np.int32), ('col2', np.int32)])
arr = np.array(df.values, dtype=dt)
</code></pre>
<p>但它给我的输出如下:</p>
<pre><code>array([[(3, 5), (3, 1)],
...
dtype=[('col1', '<i4'), ('col2', '<i4')])
</code></pre>
<p>出于某种原因,数据行被分组为<code>[(3, 5), (3, 1)]</code>,而不是<code>[(3, 5), (3, 1), (4, 5), (1, 5), (1, 2)]</code></p>