Pandas Dataframe查找所有列均等的行

Lis*_*a L 21 python pandas

我有一个数据框,其中包含字符 - 我想要一个布尔结果,告诉我该行的所有列是否具有相同的值.

例如,我有

df = [  a   b   c   d

0  'C'   'C'   'C'   'C' 

1  'C'   'C'   'A'   'A'

2  'A'   'A'   'A'   'A' ]
Run Code Online (Sandbox Code Playgroud)

我希望结果如此

0  True

1  False

2  True
Run Code Online (Sandbox Code Playgroud)

我试过.all但似乎我只能检查是否所有都等于一个字母.我能想到的另一种方法是在每一行上做一个唯一的方法,看看它是否等于1?提前致谢.

And*_*den 23

我认为最干净的方法是使用eq检查第一列的所有列:

In [11]: df
Out[11]: 
   a  b  c  d
0  C  C  C  C
1  C  C  A  A
2  A  A  A  A

In [12]: df.iloc[:, 0]
Out[12]: 
0    C
1    C
2    A
Name: a, dtype: object

In [13]: df.eq(df.iloc[:, 0], axis=0)
Out[13]: 
      a     b      c      d
0  True  True   True   True
1  True  True  False  False
2  True  True   True   True
Run Code Online (Sandbox Code Playgroud)

现在你可以使用all(如果它们都等于第一个项目,它们都相等):

In [14]: df.eq(df.iloc[:, 0], axis=0).all(1)
Out[14]: 
0     True
1    False
2     True
dtype: bool
Run Code Online (Sandbox Code Playgroud)

  • 最好把它写成 `df.eq(df.iloc[:, 0], axis=0).all(axis=1)` (3认同)

jez*_*ael 8

array按第一列进行比较,然后检查True每行是否都包含s:

numpy中的相同解决方案可提高性能:

a = df.values
b = (a == a[:, [0]]).all(axis=1)
print (b)
[ True  True False]
Run Code Online (Sandbox Code Playgroud)

如果需要Series

s = pd.Series(b, axis=df.index)
Run Code Online (Sandbox Code Playgroud)

比较解决方案:

data = [[10,10,10],[12,12,12],[10,12,10]]
df = pd.DataFrame(data,columns=['Col1','Col2','Col3'])

#[30000 rows x 3 columns]
df = pd.concat([df] * 10000, ignore_index=True)
Run Code Online (Sandbox Code Playgroud)
#jez - numpy array
In [14]: %%timeit
    ...: a = df.values
    ...: b = (a == a[:, [0]]).all(axis=1)
141 µs ± 3.23 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

#jez - Series 
In [15]: %%timeit
    ...: a = df.values
    ...: b = (a == a[:, [0]]).all(axis=1)
    ...: pd.Series(b, index=df.index)
169 µs ± 2.02 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

#Andy Hayden
In [16]: %%timeit
    ...: df.eq(df.iloc[:, 0], axis=0).all(axis=1)
2.22 ms ± 68.5 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

#Wen1
In [17]: %%timeit
    ...: list(map(lambda x : len(set(x))==1,df.values))
56.8 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

#K.-Michael Aye
In [18]: %%timeit
    ...: df.apply(lambda x: len(set(x)) == 1, axis=1)
686 ms ± 23.7 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

#Wen2    
In [19]: %%timeit
    ...: df.nunique(1).eq(1)
2.87 s ± 115 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
Run Code Online (Sandbox Code Playgroud)


WeN*_*Ben 6

nunique0.20.0版中的新功能。(基于Jez的时序基准,如果性能不重要,则可以使用此基准

df.nunique(axis = 1).eq(1)
Out[308]: 
0     True
1    False
2     True
dtype: bool
Run Code Online (Sandbox Code Playgroud)

或者你也可以使用mapset

list(map(lambda x : len(set(x))==1,df.values))
Run Code Online (Sandbox Code Playgroud)