python - 数据帧转换后保留标题

标签 python pandas numpy scikit-learn

我正在使用 sklearn 和 pandas 以及一些微阵列,并且我有一个 pandas DataFrame,每个列都已命名。所以我正在对数据框进行一些转换,本质上是特征选择。

data = pd.read_csv("data.txt")
print(data)

结果

    1007_s_at  1053_at       ...         AFFX-TrpnX-5_at  AFFX-TrpnX-M_at
0     3.96932  2.52634       ...                 2.09691          1.99123
1     4.10452  2.43457       ...                 2.28103          2.06446
2     3.95308  2.36736       ...                 2.11059          1.80618
3     3.99712  2.55388       ...                 2.13354          1.91908
4     3.95279  2.21484       ...                 2.22531          2.03342
..        ...      ...       ...                     ...              ...
96    3.79560  2.74194       ...                 2.01703          2.03743
97    3.79817  2.47422       ...                 2.12385          2.07188
98    3.84186  2.59329       ...                 2.16435          1.69897

[99 rows x 22283 columns]

正如我们所见,每一列都有一个名称。

然后我使用 VarianceThreshold 方法删除一些列

data = VarianceThreshold(0.04).fit_transform(data)
print(data)
print("After Variance Threshold data shape: ", data.shape)

所以新数据看起来像

[[4.1835  2.20952 2.41664 ... 2.21748 2.69197 2.41996]
 [3.82478 2.2878  1.69897 ... 1.87506 2.09691 2.35411]
 [4.1503  2.32015 2.35793 ... 2.01284 2.2833  2.15534]
 ...
 [3.85576 3.26694 2.71684 ... 2.68305 3.18298 2.83378]
 [3.25912 2.04922 2.58092 ... 2.0607  2.66932 2.42325]
 [3.34044 2.24551 2.60097 ... 2.03743 2.31806 2.35984]]
After Variance Threshold data shape:  (99, 5002)

现在,数据是一个 numpy 数组,我丢失了原始数据帧中剩余的每一列的标题。

有什么办法让它们与 pandas/numpy 一起保存吗?

最佳答案

您可以使用get_support得到一个掩码而不是结果:

In [11]: df = pd.DataFrame([[0, 2, 0, 3], [0, 1, 4, 3], [0, 1, 1, 3]], columns=list("ABCD"))

In [12]: df
Out[12]:
   A  B  C  D
0  0  2  0  3
1  0  1  4  3
2  0  1  1  3

In [13]: VarianceThreshold().fit(df).get_support()
Out[13]: array([False,  True,  True, False])

In [14]: df.loc[:, VarianceThreshold().fit(df).get_support()]
Out[14]:
   B  C
0  2  0
1  1  4
2  1  1

在您的示例中:

df.loc[:, VarianceThreshold(0.04).fit(data).get_support()]

关于python - 数据帧转换后保留标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54700086/

相关文章:

python - 将数据插入两列 csv

python - 高级切片 : Given a list of index, 从 numpy 数组中选取不同的元素

python - 等同于 Python 中 R 的 createDataPartition

python - 获取文本小部件的长度

python - 在哪里可以获得 python 脚本的 pymssql

python - 对 Pandas 数据框的每一列执行逻辑操作?

python - 在 Pandas 数据框中搜索和删除重复的时间序列数据

python - 如果名称在列中出现超过 n 次,则 Pandas 过滤器

python - Pandas rolling_quantile 错误?

python - 如何通过调整权重来优化 PIL 逊相关系数?