简体   繁体   中英

Unpacking a numpy array into columns of a pandas df

I have a numpy array as follows:

array([(26, 8, 32), (2, 2, 1), (4, 5, 3), (3, 3, 2), (3, 1, 5), (4, 4, 3),
       (4, 2, 10), (31, 10, 58), (7, 7, 4)], dtype=object)

I want to unpack this into a dataframe such that

Col1   Col2   Col3
26      8     32
2       2      1
4       5      3
3      3       2
3      1       5
4      4       3
4      2       10
31    10       58
7     7        4

Infact this output is being generated by using an apply function on an existing df and returning 3 values. So would be fantastic, if I can assign the 3 values into the columns of the df directly (versus storing in an array)... Thanks!

It works for me:

import numpy as np
import pandas as pd

a = np.array([(26, 8, 32), (2, 2, 1), (4, 5, 3), (3, 3, 2), (3, 1, 5), (4, 4, 3),
              (4, 2, 10), (31, 10, 58), (7, 7, 4)], dtype=object)

df = pd.DataFrame(a, columns=['A','B','C'])
print(df)

output:

    A   B   C
0  26   8  32
1   2   2   1
2   4   5   3
3   3   3   2
4   3   1   5
5   4   4   3
6   4   2  10
7  31  10  58
8   7   7   4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM