gpt4 book ai didi

python - 如果列中的所有条目都与 Pandas 列表中的项目匹配,则删除列

转载 作者:太空宇宙 更新时间:2023-11-03 14:03:49 24 4
gpt4 key购买 nike

我有一个数据框,我试图根据其内容从中删除一些列。如果列中的所有行与列表中的一项具有相同的值,那么我想删除该列。我很难在不搞乱循环的情况下做到这一点。有没有更好的方法来做到这一点,或者我可以修复一些错误?我收到一条错误消息:

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()

最佳答案

Loopy 通常不适合与 pandas 一起使用。这是一种解决方案。

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

关于python - 如果列中的所有条目都与 Pandas 列表中的项目匹配,则删除列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49059715/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com