首页 > 解决方案 > 熊猫数据框比较索引的所有列值而没有列名参考

问题描述

我有一个包含许多列的索引数据框,一些示例:

    Feature1
    Feature2
    Feature3
    Feature4
....

我只想实现一个函数,创建一个新的数据框(或另一种数据结构类型)对象,如果值相等,它将一个测试样本行值与所有其他行(包括测试样本)的值进行比较;比较结果将是“1”,否则为“0”,但由于我有 91 列,我不想引用列名,我见过很多例子,列名被赋予某些 pandas 函数。

分类数据对象的数据示例(NaN 表示null

_product Feature1 Feature2 Feature3 Feature4
SRI3012  1        yes         IN    NaN
SRI3015  1        yes         IN    NaN
SRS3012  1        no          OUT   Val1

我只是尝试过:

##Choose sample
    test_sample = classified_data.sample();
#Find index of random sample
    test_product_code = list(test_sample.index.values)[0]
##Find location of random product in data-set
    test_index = classified_data.index.get_loc(test_product_code)
    #print(test_sample);
    #print(classified_data[(test_index):(test_index+1)])
    enum_similarity_data = pandas.DataFrame(calculate_similarity_for_categorical(classified_data[(test_index):(test_index+1)],classified_data).T,index=classified_data.index)


def calculate_similarity_for_categorical(value1,value2):
    if(value1 == value2):
        return 1;
    else:
        return 0;

SRI3012 的所需输出(假设随机选择)数据框或具有列名称和值的另一个对象:

_product Feature1 Feature2 Feature3 Feature4
SRI3012  1        1        1        1
SRI3015  1        1        1        1
SRS3012  1        0        0        0

标签: pythonpandas

解决方案


DataFrame.eq

您可以检查一行与所有其他行的相等性,指定axis=1. 这里的比较应该是DataFrame.eq(Series, axis=1)如果你认为NaN == NaNTrue(这不是标准)我们需要单独处理。

import pandas as pd
import numpy as np
df = pd.DataFrame([['A', 'A', 'B', 'C', np.NaN], ['A', 'A', 'B', 'C', np.NaN], 
                   ['A', 'X', 'Z', 'C', np.NaN], [6, 'foo', 'bar', 12, 1231.1]])
#   0    1    2   3       4
#0  A    A    B   C     NaN
#1  A    A    B   C     NaN
#2  A    X    Z   C     NaN
#3  6  foo  bar  12  1231.1

s = df.iloc[0]  # or df.iloc[np.random.choice(range(df.shape[0]))]
(df.eq(s, axis=1) | (s.isnull() & df.isnull())).astype(int)
                     # so NaN == NaN is True

#   0  1  2  3  4
#0  1  1  1  1  1
#1  1  1  1  1  1
#2  1  0  0  1  1
#3  0  0  0  0  0

推荐阅读