我试图删除我的数据框架中没有一个值高于。9的任何列。我知道这可能不是最有效的方法,但我找不到问题所在。我知道它是不正确的,因为它只删除了一列,我知道它应该更接近20。因此,我进行计数,看看有多少值低于。9,然后,如果计数等于列值列表的长度,则删除该列。提前谢谢。
for i in range(len(df3.columns)):
count=0
for j in df3.iloc[:,i].tolist():
if j<.9:
count+=1
if len(df3.iloc[:,i].tolist())==count:
df4=df3.drop(df3.columns[i], axis=1)
df4
您可以遍历数据框架中的每个列,并根据定义的阈值检查每个列中的最大值,在本例中为0.9,如果没有超过0.9的值,则删除该列。
输入:
col1 col2 col3
0 0.2 0.8 1.0
1 0.3 0.5 0.5
代码:
# define dataframe
df = pd.DataFrame({'col1':[0.2, 0.3], 'col2':[0.8, 0.5], 'col3':[1, 0.5]})
# define threshold
threshold = 0.9
# loop through each column in dataframe
for col in df:
# get the maximum value in column
# check if it is less than or equal to the defined threshold
if df[col].max() <= threshold:
# if true, drop the column
df = df.drop([col], axis=1)
这个输出:
col3
0 1.0
1 0.5