python - 熊猫数据框比较索引的所有列值而没有列名参考
问题描述
我有一个包含许多列的索引数据框,一些示例:
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
解决方案
DataFrame.eq
您可以检查一行与所有其他行的相等性,指定axis=1
. 这里的比较应该是DataFrame.eq(Series, axis=1)
如果你认为NaN == NaN
是True
(这不是标准)我们需要单独处理。
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
推荐阅读
- postgresql - 等待状态显示缓冲区引脚
- c - 当 xTicksToWait = portMAX_DELAY 时,xQueueReceive 会失败吗?
- python - python'jwt'模块没有属性'encode'
- java - 限制用户在 java swing 中打开的 jframe 不超过 1 个
- java - 为什么不触发 Firebase 中的 onDisconnect?
- ios - 我可以在 SFSafariViewController 中从 Safari 获取 cookie 吗?
- java - 如何验证json的每个对象和键值
- c# - 在 Foreach 循环中填充的 SSIS 对象变量设置为循环外的最后一行,无法访问整个数组
- assembly - 线性,物理,逻辑和虚拟内存地址有什么区别?
- go - Go r.PostForm 为空