【问题标题】:Convert numpy ndarray to non-numpy datatype将 numpy ndarray 转换为非 numpy 数据类型
【发布时间】:2014-02-07 17:48:36
【问题描述】:

我正在尝试将np.ndarray 的元素转换为本机整数类型。

>>> x = np.array([1, 2, 2.5])
>>> type(x[0])
<type 'numpy.float64'>
>>> type(x.astype(int)[0])
<type 'numpy.int64'>

我想要的是:

>>> type(x.astype('something here')[0])
<type 'int'>

这是在pandas 上下文中提出的原始问题,但结果归结为np.ndarray.astype() 的问题

astype(int) 维护 Series 中整数的 numpy-ness:

>>> s = pd.Series([1,2,3])
>>> type(s[0])
<type 'numpy.int64'>
>>> type(s[0].astype(int))
<type 'numpy.int64'>

有没有办法将一个系列,甚至只是一个系列的一个元素转换为原生数据类型,以便实现以下目标?

>>> type(s[0].dosomething())
<type 'int'>

我为什么要问这个?

我正在尝试使用 networkx.write_gexf()pandas.DataFrame 导出为 GEXF 格式。

出口商坚持所有使用的数据都以intfloatbool 或其他一些方式响应type(x)。它不知道如何处理numpy.int64

【问题讨论】:

  • 假设df 是您的DataFrame,为什么不先使用g = nx.from_numpy_matrix(df.values) 将您的DataFrame 转换为NetworkX 对象?那么就只是nx.write_gexf(g, path)?
  • (嗨,Rob,我是 Stephan)
  • 我正在尝试将属性添加到我的边缘。 nx.set_edge_attributes(G, 'myattr', df['attribute'].astype(int).to_dict()) 工作正常,但随后 nx.write_gexf() 抱怨。
  • 嗯。事后我从未添加过属性,只是一次从 df 构建它,然后重新标记它。
  • @DSM 是对的,设置 dtype=object 将数据从基本的 numpy 类型更改为 python 对象(实际上它并没有更改它,但允许它改变)。当然,object dtypes 上的操作性能会低得多(但如果你想把数据取出来,可能会比 2 u 更重要)

标签: numpy pandas networkx


【解决方案1】:

根据 cmets,您可能不需要这个,但要回答当前的问题,您可以使用 item 方法。例如:

In [78]: x = np.array([1.0, 2.0, 3.0])

In [79]: x.dtype
Out[79]: dtype('float64')

In [80]: x.item(0)
Out[80]: 1.0

In [81]: type(x.item(0))
Out[81]: float

In [82]: y = np.array([1, 2, 3], dtype=np.int32)

In [83]: type(y.item(0))
Out[83]: int

In [84]: type(y[0])
Out[84]: numpy.int32

要一次转换整个数组,tolist 方法会将元素转换为最接近的兼容 Python 类型:

In [95]: xlist = x.tolist()

In [96]: xlist
Out[96]: [1.0, 2.0, 3.0]

In [97]: type(xlist[0])
Out[97]: float

In [98]: ylist = y.tolist()

In [99]: ylist
Out[99]: [1, 2, 3]

In [100]: type(ylist[0])
Out[100]: int

【讨论】:

    猜你喜欢
    • 2018-08-14
    • 2017-12-14
    • 2015-08-07
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2015-12-17
    • 1970-01-01
    • 2017-10-05
    相关资源
    最近更新 更多