python - 从 pandas 转换为 numpy 时如何保留列名

标签 python pandas numpy

根据to this post ,我应该能够访问 ndarray 中列的名称作为 a.dtype.names

但是,如果我使用 df.as_matrix() 或 df.values 将 pandas DataFrame 转换为 ndarray,则 dtype.names 字段为 None。此外,如果我尝试将列名分配给 ndarray

X = pd.DataFrame(dict(age=[40., 50., 60.], sys_blood_pressure=[140.,150.,160.]))
print X
print type(X.as_matrix())# <type 'numpy.ndarray'>
print type(X.as_matrix()[0]) # <type 'numpy.ndarray'>

m = X.as_matrix()
m.dtype.names = list(X.columns)

我明白了

ValueError: there are no fields defined

更新:

我对矩阵只需要保存单一类型(它是特定数字类型的 ndarray)的情况特别感兴趣,因为我也想使用 cython 进行优化。 (我怀疑 numpy 记录和结构化数组更难处理,因为它们的类型更自由。)

真的,我只是想为通过 sci-kit 预测器的深层树传递的数组维护 column_name 元数据。其接口(interface)的 .fit(X,y) 和 .predict(X) API 不允许在 X 和 y 对象之外传递有关列标签的额外元数据。

最佳答案

考虑如下所示的 DF:

X = pd.DataFrame(dict(one=['Strawberry', 'Fields', 'Forever'], two=[1,2,3]))
X

enter image description here

提供一个元组列表作为结构化数组的数据输入:

arr_ip = [tuple(i) for i in X.as_matrix()]

字段名称的有序列表:

dtyp = np.dtype(list(zip(X.dtypes.index, X.dtypes)))

在这里,X.dtypes.index 为您提供列名,X.dtypes 是相应的数据类型,它们再次统一到一个元组列表 并作为输入提供给要构造的 dtype 元素。

arr = np.array(arr_ip, dtype=dtyp)

给出:

arr
# array([('Strawberry', 1), ('Fields', 2), ('Forever', 3)], 
#       dtype=[('one', 'O'), ('two', '<i8')])

arr.dtype.names
# ('one', 'two')

关于python - 从 pandas 转换为 numpy 时如何保留列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40554179/

相关文章:

python - df [‘’ ] 和 df[ [‘’ ]] 有什么区别

python - Pandas str.count()

python - Pandas read_excel : nan values forcing others in the same column to be converted to float

python - 使用 openpyxl 导出数据帧时出现空行

python - 从 NumPy 二维数组中删除重复的列和行

python - 如何拆分/ reshape 一个 numpy 数组

python - C++:从用户输入调用函数

python - BeautifulSoup Python 脚本不再适用于挖掘简单的字段

python - 如何跟踪 csr 矩阵

python - 单独训练和部署