【问题标题】:How to convert a numpy matrix to a pandas series?如何将 numpy 矩阵转换为 pandas 系列?
【发布时间】:2016-08-26 10:31:46
【问题描述】:

我有以下 numpy 矩阵:

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

我想得到以下信息:

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

我的目的是将 numpy.array 中的每一行转换为一个字符串 将用于熊猫数据框。 是否有一些内置的 pandas 功能可以救援?

【问题讨论】:

  • 58, 64 怎么了?简短回答您的问题,因为您想将dtype 转换为str,然后连接行值

标签: python arrays numpy pandas


【解决方案1】:

IIUC你可以使用DataFrame构造函数和applyjoin

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

【讨论】:

  • 如何为创建的数据框添加名称?
  • 您认为列的名称 - 不是 01 ,而是 col1col2?或者Serie的名字(print df.apply(lambda x: ' '.join(x), axis=1))
  • 我想给创建的行一个标签。
猜你喜欢
  • 2014-12-19
  • 2018-07-25
  • 2015-04-30
  • 2017-04-11
  • 2012-08-28
  • 2017-05-17
  • 2017-01-29
  • 2014-12-21
  • 1970-01-01
相关资源
最近更新 更多