python - 比较 Pandas Dataframes 的 boolean 值——返回字符串

标签 python pandas boolean dataframe

我要比较 4 个数据框,每个看起来都像

ID    Jan    Feb    Mar
1     True   True   False
2     True   True   True
3     False  False  False

2 到 3000 行之间的任意位置。它们将具有完全相同的列名,但可能并不总是共享所有相同的索引 ID。

我想做的是比较它们并根据它们的值生成一个新的数据框。对于至少在一个数据框中为 False 的任何单元格,我想为其分配一个字符串(例如“Dataframe1 中的 False”),如果有多个,则附加两者(例如“Dataframe1 中的 False,Dataframe2”)。

输出看起来像

ID    Jan            Feb              Mar
1     True           True             False in A, B, C
2     True           False in B       True
3     False in A     False in A, B    False in A

我可以使用某种直接的数据帧与数据帧比较吗?或者我是否需要连接数据帧以便我可以将列相互比较?

编辑-我不想按行比较,而是基于索引,以应对一个数据帧没有相同记录的情况。

最佳答案

非常接近,你想要什么:

import pandas as pd
import numpy as np
import io

#testing df1,df2,df3
temp=u"""ID,Jan,Feb,Mar
1,True,True,False
2,True,True,True
3,False,False,False"""
df3 = pd.read_csv(io.StringIO(temp), sep=",", index_col=[0])
print df3
temp1=u"""ID,Jan,Feb,Mar
1,True,False,False
2,False,True,True
3,False,True,True"""
df1 = pd.read_csv(io.StringIO(temp1), sep=",", index_col=[0])
print df1
temp2=u"""ID,Jan,Feb,Mar
1,False,False,False
2,False,False,True
3,False,True,True"""
df2 = pd.read_csv(io.StringIO(temp2), sep=",", index_col=[0])
print df2

#concat all dataframes by columns
pieces = {'df1': df1, 'df2': df2, 'df3': df3}
df = pd.concat(pieces, axis=1)
print df

#create new dataframe with size as df filled by column names
levels = df.columns.levels
labels = df.columns.labels
xyz = pd.DataFrame( np.array(levels[0][labels[0]].tolist()*len(df.index)).reshape((len(df.index), len(df.index)*len(pieces))), index=df.index, columns = df.columns)
print xyz

#reset multicolumn to column
xyz.columns = levels[1][labels[1]]
df.columns = levels[1][labels[1]]

#use df as mask - output names of df with False
print xyz.mask(df)

#use df as mask - output names of df with True
out_false =  xyz.mask(df)
print out_false

out_true =  xyz.mask(~df)
print out_true

#create output empty df - for False and for True values
result_false = result_true = pd.DataFrame(index = out_false.index)

#group output dataframe by columns and create new df from series - for False and for True values
for name, group in out_false.groupby(level=0, axis=1):
    #print name
    series = pd.Series(group.apply(lambda x: ','.join(map(str, x.dropna())), axis=1), name=name)
    print
    print series
    result_false = pd.concat([result_false, series], axis=1) 
print result_false   
#        Feb          Jan          Mar
#ID                                   
#1   df1,df2          df2  df1,df2,df3
#2       df2      df1,df2             
#3       df3  df1,df2,df3          df3 

for name, group in out_true.groupby(level=0, axis=1):
    #print name
    series = pd.Series(group.apply(lambda x: ','.join(map(str, x.dropna())), axis=1), name=name)
    result_true = pd.concat([result_true, series], axis=1) 
print result_true  
#        Feb      Jan          Mar
#ID                               
#1       df3  df1,df3             
#2   df1,df3      df3  df1,df2,df3
#3   df1,df2               df1,df2

关于python - 比较 Pandas Dataframes 的 boolean 值——返回字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33905944/

相关文章:

python - 将空目录添加到 tarfile

python - 格式化字典中的python字典以导出到excel

python - 从python中的多索引数据框中获取索引号

python - 为什么我在 codewars python 中遇到问题时出错?

python - 合并这些数据框时的 Nan 值

python - 不要跳过 pandas.read_excel() 中的空白行

java - Java 中的 Boolean.TRUE 和 true 有什么区别?

java - 为什么我会收到 java.util.InputMismatchException?

javascript - 将一组 "true" boolean 值变量转换为数组

python - 将 ctypes 与 cuda 结合使用,在脚本末尾出现段错误(核心转储)错误