我有一个数据框,我试图根据其内容删除一些列。如果列中的所有行与列表中的某个项具有相同的值,那么我想删除该列。我无法在不搞乱循环的情况下做到这一点。有没有更好的方法来做到这一点,或者我可以修复一些错误?我收到的错误是:
IndexError: index 382 is out of bounds for axis 0 with size 382
码:
def trimADAS(df):
notList = ["Word Recall Test","Result"]
print("START")
print(len(df.columns))
numCols = len(df.columns)
for h in range(numCols): # for every column
for i in range(len(notList)): # for every list item
if df[df.columns[h]].all() == notList[i]: # if all column entries == list item
print(notList[i]) # print list item
print(df[df.columns[h]]) # print column
print(df.columns[h]) # print column name
df.drop([df.columns[h]], axis = 1, inplace = True) # drop this column
numCols -= 1
print("END")
print(len(df.columns))
print(df.columns)
return()
松鼠通常不是大熊猫的方式。这是一个解决方案。
import pandas as pd
df = pd.DataFrame({'A': [1, 1, 1, 1],
'B': [2, 2, 2, 2],
'C': [3, 3, 3, 3],
'D': [4, 4, 4, 4],
'E': [5, 5, 5, 5]})
lst = [2, 3, 4]
df = df.drop([x for x in df if any((df[x]==i).all() for i in lst)], 1)
# A E
# 0 1 5
# 1 1 5
# 2 1 5
# 3 1 5