【问题标题】:How to select the same columns of a numpy array based on indices of a second array如何根据第二个数组的索引选择 numpy 数组的相同列
【发布时间】:2017-12-07 18:00:21
【问题描述】:

我需要根据前一个中的选定列过滤数据帧或 numpy 数组,即过滤与第一个数组中的列相同的列。

这是我的方法:

排除零变量(过滤、选择第一个 df 中的列)

df_NN_70 = df_NN_70.loc[:, (df_NN_70 != df_NN_70.ix[0]).any()]

抽样(分离 70% 的数据用作训练/测试集)

df_NN = df_NN_70.sample(frac=0.7, replace=False, weights=None, random_state=seed, axis=None)

在 NN 中使用 keras 转换为数组(它需要数组)

df_NN_array = df_NN.as_matrix(columns=None)

将数据拆分为输入 (X) 和输出 (Y) 变量

X = df_NN_array[:, 0:df_NN_array.shape[1]-1]
Y = df_NN_array[:, 427]

print(type(df_NN_70.columns))
index_list= list(df_NN_70.columns)

index_list = index_list[0:427]
print(index_list)

根据从df_NN_x获取的列列表,一秒过滤相同的列

filter_columns = index_list
df_filtered = np.array(df_NN_x)[filter_columns]
new.shape

但是,此过滤不起作用,因为它将index_list 视为第二个数组df_NN_x 中行的索引,而不是列!

【问题讨论】:

    标签: python arrays pandas numpy filtering


    【解决方案1】:

    需要在数组的第二维进行过滤,例如:

    df_filtered = np.array(df_NN_x).ix[:, filter_columns]
    

    或:

    df_filtered = np.array(df_NN_x)
    df_filtered = df_filtered[df_filtered.columns[filter_columns]]
    

    请注意,第一个版本包含 filter_columns-list 的最后一个元素,第二个不包含。

    编辑:我的答案是一个 numpy 数组,将其更新为 pandas。

    【讨论】:

    • 谢谢@Nyps。第一行代码使用 pandas df 为我工作。
    猜你喜欢
    • 1970-01-01
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多