比较没有columnname引用的索引的所有列值

2024-04-26 23:03:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含许多列的索引数据帧,例如:

    Feature1
    Feature2
    Feature3
    Feature4
....

我只想实现一个函数,创建一个新的dataframe(或另一个数据结构类型)对象,如果值相等,它将比较一个测试样本行值和所有其他行(包括测试样本)的值;比较结果将是“1”或“0”,但由于我有91列,我不想引用列名,我见过许多例子,其中一些函数使用列名。你知道吗

分类数据对象的数据示例(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

Tags: 数据sample对象testdataindexnanproduct
2条回答

我不能评论,所以我在这里评论。正如Quang Hoang所评论的,您不应该使用screanshots,而应该使用简单且格式良好的数据,任何花费宝贵时间帮助您的人都可以复制这些数据。而且,所有这些复杂的信息都是不必要的。你可以用一个简单的虚拟数据框和简单的值和名称来重现问题的概念。这样你会得到更好更快的答案。你知道吗

试试这个:

import numpy as np
import pandas as pd


df = pd.DataFrame({'Feature1':[    1 ,     1 ,    1 ],
                   'Feature2':[ 'yes',  'yes',  'no'], 
                   'Feature3':[ 'IN' ,  'IN' , 'OUT'],
                   'Feature4':[np.NaN, np.NaN,    5 ]
                  },
                  index=['SR12', 'SR13', 'SR14']
)
df.index.name = '_product'

def compare_against_series(x, reference):
    """compares a Series against a reference Series"""
    # apply .astype(int) to convert boolean to 0-1
    return np.logical_or(x == sample, x.isnull() & sample.isnull()).astype(int)

# take the 1st row as sample 
sample = df.iloc[0]

# apply compare_against_series row-wise, using the sample
# note axis=1 means row-wise and axis=0 column-wise
result = df.apply(compare_against_series, axis=1, reference=sample)

测向:

          Feature1 Feature2 Feature3 Feature4
_product                            
SR12             1      yes       IN      NaN
SR13             1      yes       IN      NaN
SR14             1       no      OUT      5.0

样品:

Feature1      1
Feature2    yes
Feature3     IN
Feaure4     NaN
Name: SR12, dtype: object

结果:

          Feature1  Feature2  Feature3  Feautre4
_product                              
SR12             1         1         1         1
SR13             1         1         1         1
SR14             1         0         0         0

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

相关问题 更多 >