![](/img/trans.png)
[英]Python: How to iterate through a range of columns in a dataframe, check for specific values and store column name in a list
[英]Python Dataframe: How to check specific columns for elements
您可以使用 0 元素檢查相等性並將all
用於行:
df['all_zeros'] = (df.iloc[:, 4:1560] == 0).all(axis=1)
演示它的小示例(基於此處的第 1 到 3 列):
N = 5
df = pd.DataFrame(np.random.binomial(1, 0.4, size=(N, N)))
df['all_zeros'] = (df.iloc[:, 1:4] == 0).all(axis=1)
df
Output:
0 1 2 3 4 all_zeros
0 0 1 1 0 0 False
1 0 0 1 1 1 False
2 0 1 1 0 0 False
3 0 0 0 0 0 True
4 1 0 0 0 0 True
更新:過濾非零值:
df[~df['all_zeros']]
Output:
0 1 2 3 4 all_zeros
0 0 1 1 0 0 False
1 0 0 1 1 1 False
2 0 1 1 0 0 False
更新 2:僅顯示非零值:
pd.melt(
df_filtered.iloc[:, 1:4].reset_index(),
id_vars='index', var_name='column'
).query('value != 0').sort_values('index')
Output:
index column value
0 0 1 1
3 0 2 1
4 1 2 1
7 1 3 1
2 2 1 1
5 2 2 1
df['Check']=df.loc[:,4:].sum(axis=1)
這是檢查所有值是否為零的方法:它很簡單,不需要上述答案的高級功能。 只有基本功能,如過濾和 if 循環和變量分配。
首先是檢查一列是否只有零的方法,其次是如何查找所有列是否都為零。 它打印和回答聲明。
檢查一列是否只有零值的方法:
先做一個系列:
has_zero = df[4] == 0
# has_zero is a series which contains bool values for each row eg. True, False.
# if there is a zero in a row it result will be "row_number : True"
下一個:
rows_which_have_zero = df[has_zero]
# stores the rows which have zero as a data frame
下一個:
if len[rows_which_have_zero] == total_number_rows:
print("contains only zeros")
else:
print("contains other numbers than zero")
# substitute total_number_rows for 3220
上述方法僅檢查 rows_which_have_zero 是否等於列中的行數。
查看所有列是否只有零的方法:
它使用上面的 function 並將其放入 if 循環中。
no_of_columns = 1559
value_1 = 1
if value_1 <= 1559
has_zero = df[value_1] == 0
rows_which_have_zero = df[has_zero]
value_1 += 1
if len[rows_which_have_zero] == 1559
no_of_rows_with_only_zero += 1
else:
return
檢查所有行是否只有零:
#since it doesn't matter if first 3 columns have zero or not:
no_of_rows_with_only_zero = no_of_rows_with_only_zero - 3
if no_of_rows_with_only_zero == 1559:
print("there are only zero values")
else:
print("there are numbers which are not zero")
上面檢查 no_of_rows_with_only_zero 是否等於行數(即 1559 減去 3,因為只需要檢查第 4 - 1559 行)
更新:
# convert the value_1 to str if the column title is a str instead of int
# when updating value_1 by adding: convert it back to int and then back to str
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.