【发布时间】: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 格式。
出口商坚持所有使用的数据都以int、float、bool 或其他一些方式响应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 对象(实际上它并没有更改它,但允许它改变)。当然,objectdtypes 上的操作性能会低得多(但如果你想把数据取出来,可能会比 2 u 更重要)