我有以下的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函数可以帮助实现此目的?
如果我理解正确,您可以使用 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
col1
和col2
而不是0
和1
吗?或者Serie
的名称是什么(print df.apply(lambda x: ' '.join(x), axis=1)
)? - jezrael
58, 64
发生了什么?简短回答你的问题是不行的,因为你想要将dtype
转换为str
,然后连接行值。 - EdChum