如何将NumPy矩阵转换为Pandas Series?

5

我有以下的numpy矩阵:

array([[64, 22,],
   [58, 64],
   [42, 31])

And i want to get the following:

pd.DataFrame({'one':"64 22", 'two':"42 31"})

我的目的是将numpy.array中的每一行转换为字符串,以便在pandas数据框中使用。 是否有一些内置的pandas函数可以帮助实现此目的?


58, 64 发生了什么?简短回答你的问题是不行的,因为你想要将 dtype 转换为 str,然后连接行值。 - EdChum
1个回答

5

如果我理解正确,您可以使用 DataFrame 构造函数和 apply 方法的 join 功能:

import pandas as pd
import numpy as np

arr = np.array([[64, 22,],   [58, 64],   [42, 31]])
print arr
[[64 22]
 [58 64]
 [42 31]]

li = ['one','two','three']
df = pd.DataFrame(arr, dtype='str', index=li)
print df
        0   1
one    64  22
two    58  64
three  42  31

print df.apply(lambda x: ' '.join(x), axis=1)
one      64 22
two      58 64
three    42 31
dtype: object

我该如何向创建的数据框中添加名称? - avicohen
你认为列的名称应该是col1col2而不是01吗?或者Serie的名称是什么(print df.apply(lambda x: ' '.join(x), axis=1))? - jezrael
我想给创建的行添加一个标签。 - avicohen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接