python - 使用python删除矩阵中的相应行/列

标签 python pandas numpy matrix

我正在使用 pandas/numpy 处理 1400x1400 相关矩阵,我的目标是删除使用给定变量名称的行和列。每行和每列都有变量的名称以及这两个变量之间的相关性:

            abandon abhorrent abominable
abandon     1.00    0.12      0.10
abhorrent   0.12    1.00      0.99
abominable  0.10    0.99      1.00

要将数据帧转换为矩阵,我使用 as_matrix:

datafile = pd.read_csv('data.csv')
df_matrix = datafile.as_matrix

我无法理解如何在不包括变量“abandon”(即删除对应于“abandon”的列和行)的情况下创建新数据框。

开始时,我尝试只选择一个列来了解如何创建我想要的变量列表:

df_matrix = datafile.as_matrix(columns=['abhorrent'])

然而,这只返回数组,我丢失了所有的行/列名称。

我还尝试在导入数据后删除行/列。这将需要我采取额外的步骤来形成一个我不需要的变量名列表,然后将它们作为列/行号传递,但这似乎是可行的。但是我不确定这段代码是否完全正确:

df_matrix2 = np.delete(df_matrix, 1, axis=0)
df_matrix2 = np.delete(df_matrix, 1, axis=1)

据我所知,这段代码没有在新矩阵中产生任何变化。它仍然是一个 1400x1400 矩阵。

最佳答案

你可以使用DataFrame.drop()方法:

In [9]: df
Out[9]:
            abandon  abhorrent  abominable
abandon        1.00       0.12        0.10
abhorrent      0.12       1.00        0.99
abominable     0.10       0.99        1.00

In [10]: df.drop('abandon', 1).drop('abandon')
Out[10]:
            abhorrent  abominable
abhorrent        1.00        0.99
abominable       0.99        1.00

关于python - 使用python删除矩阵中的相应行/列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42353678/

相关文章:

Python,在列中拆分多个字符串

python - 无法 reshape numpy 数组

python - 使用 matplotlib 绘制列表中的函数

python - Dask Kubernetes Worker Pod 给出错误状态

python - Tensorflow导入错误: No module named 'tensorflow'

python - 设置字符串格式以方便阅读和打印

python - 多处理池和 Lightgbm

python-3.x - 如何使用 pandas 数据框中的列来标记气泡图/散点图?

python - Pandas read_json : "If using all scalar values, you must pass an index"

python - Matplotlib 填充权重步骤图