【问题标题】:Extracting data from pandas based on condition根据条件从熊猫中提取数据
【发布时间】:2018-09-25 13:15:59
【问题描述】:

我有一个数据框A = [1,2,3,5,9,8,11,13] and B = [2,1,6,19,16,15,14,12]。我想要检查的是 A 和 B 的纵横交错元素在任何情况下是否相等

例如:这里A[0]==B[1] and B[0]==A[1],这是一个纵横交错的元素。

import pandas as pd
df=pd.DataFrame({'A':[1,2,3],'B':[2,1,6]})
if df.loc[0,"A"] == df.loc[1,"B"] & df.loc[1,"A"] == df.loc[0,"B"]:
    print("the values which are equal")
else:
    print("the values which are not equal")

【问题讨论】:

  • 您只想检查一个条件?那你为什么要遍历ij
  • 您可能希望使用loc,例如在您的代码中尝试:if df.loc[0,"A"] == df.loc[1,"B"] and df.loc[1,"A"] == df.loc[0, "B"]:
  • 我想遍历数据框中的所有元素(即跨 A 和 B)
  • 我不清楚你的意思。还有哪些元素?您能edit您的问题并指定您要进行的所有比较吗?
  • 您要检查第 0 行和第 1 行的对角线,然后是第 1 行和第 2 行等吗?

标签: python pandas loops indexing


【解决方案1】:

比较连续的列

为了检查数据帧中所有行的A[i]==B[i+1] & A[i+1]==B[i] 是否,您可以对列进行矢量比较但移位:

A = np.array([1,2,3,5,14,16,16,13]) # I mdified input data from the question for the second example
B = [2,1,6,19,16,15,14,12]
df = pd.DataFrame({'A':A,'B':B})
eq_diag = (df['A'][:-1].values==df['B'][1:].values) & (df['A'][1:].values==df['B'][:-1].values)
# boolean array with rows=rows_in_df-1, eq_diag[i] will be true if the 
# diagonal between rows i and i+1 is equal
# Output for eq_diag
# [ True False False False False False False]

然后,可以打印这些对角线比较中相等的值:

print df[:-1][eq_diag] # the [:-1] is important for dimensions to match
# Out
    A  B
 0  1  2 # it also returns the index i (not i+1) where the diagonal is equal

比较数据框中的 ALL 列组合

如果不是比较列i 与列i+1,而是比较所有可能的组合,则可以使用模块itertools

import itertools
combinations =  np.array(list(itertools.combinations(range(len(df)),2)))
print combinations.T
eq_diag = ((df['A'].values[combinations[:,0]]==df['B'].values[combinations[:,1]]) & 
           (df['A'].values[combinations[:,1]]==df['B'].values[combinations[:,0]]))
# Out: all the column combinations
[[0 0 0 0 0 0 0 1 1 1 1 1 1 2 2 2 2 2 3 3 3 3 4 4 4 5 5 6]
 [1 2 3 4 5 6 7 2 3 4 5 6 7 3 4 5 6 7 4 5 6 7 5 6 7 6 7 7]]

然后,可以打印相等的元素:

for i,j in combinations[eq_diag]:
    print 'The criss cross element of columns {} and {} is equal:\n{}'.format(i,j,df.values[[i,j]])
# Out
# The criss cross element of columns 0 and 1 is equal:
# [[1 2]
#  [2 1]]
# The criss cross element of columns 4 and 6 is equal:
# [[14 16]
#  [16 14]]

【讨论】:

  • @Amit 我更新了答案以考虑所有可能的列组合的情况。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-06-26
  • 2023-03-21
  • 2019-03-24
  • 2018-12-13
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多