如何将 numpy 矩阵转换为 Pandas 系列?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/36969235/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert a numpy matrix to a pandas series?
提问by avicohen
I have the following numpy matrix:
我有以下 numpy 矩阵:
array([[64, 22,],
[58, 64],
[42, 31])
And i want to get the following:
我想得到以下内容:
pd.DataFrame({'one':"64 22", 'two':"42 31"})
My purpose is to convert each row in the numpy.array to a string that will be used for a pandas dataframe. Is there some built in pandas function to the rescue?
我的目的是将 numpy.array 中的每一行转换为将用于Pandas数据帧的字符串。是否有一些内置的Pandas功能来救援?
采纳答案by jezrael
IIUC you can use DataFrame
constructor and apply
join
:
IIUC 您可以使用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