python - Pandas as_matrix() 使值保持列顺序

标签 python pandas

我目前使用 .as_matrix() 函数来确保 numpy 数组保持正确的列顺序;然而,这是要折旧的。一旦使用建议的 .values 函数折旧 as_matrix 函数,如何确保保持列顺序?或者还有其他方法吗?

非常感谢

as_matrix 示例

In: prices.pct_change()[1:].as_matrix(stocks)

Out: array([-0.00283364,  0.0012285 ,  0.0014199 ,  0.00142983, -0.0053432 ])

带有值的示例

In: prices.pct_change()[1:].values

Out: array([ 0.00142983,  0.0014199 , -0.00283364, -0.0053432 ,  0.0012285 ])

最佳答案

正如您所指出的,.as_matrix() 已被弃用。 (参见下文与 .values 的比较。)

无论如何,似乎您可以先使用 .loc 按各自的顺序获取列:

import pandas as pd
import numpy as np
np.random.seed(444)

prices = pd.DataFrame(np.random.randn(200, 4), columns=list('abcd'))
columns = list('cad')
prices.pct_change().dropna().loc[:, columns].values

这是source对于 .as_matrix().values。您只会注意到细微的差别:

def as_matrix(self, columns=None):
    warnings.warn("Method .as_matrix will be removed in a future version. "
                      "Use .values instead.", FutureWarning, stacklevel=2)
    self._consolidate_inplace()
    return self._data.as_array(transpose=self._AXIS_REVERSED,
                               items=columns)

@property
def values(self):
    self._consolidate_inplace()
    return self._data.as_array(transpose=self._AXIS_REVERSED)

因此,如果您确实愿意,您可以重新创建 .as_matrix() 而不会出现警告。 (但我强烈喜欢第一种方法;它是公共(public) API;它不会让您自己处理 Pandas 内部 Block 类型。)

chg = prices.pct_change().dropna()
val = chg._data.as_array(transpose=chg._AXIS_REVERSED, items=columns)
assert np.allclose(val, prices.pct_change().dropna().loc[:, columns].values)

关于python - Pandas as_matrix() 使值保持列顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53309250/

相关文章:

python - 导出tensorflow模型时为"Cannot infer num from shape"

python - 使用 Pandas/matplotlib 绘制日均值时更改日期时间刻度的格式

python - 如何在 PyCharm 中下载文件而不是 Colab 中的 !wget?

python - argparse参数顺序

python - py.test 2.3.5 : generative tests that use fixtures?

python - 在 kedro 中将 csv 转换为 parquet

python - Pandas:将一行中的 nan 转换为空数组

python - 如何展平pandas数据框中的数组

json - 使用 Pandas .to_sql 将 JSON 列写入 Postgres

python - 无法导入normalize_corpus python 3