簡體   English   中英

Python Dataframe:如何檢查特定列的元素

[英]Python Dataframe: How to check specific columns for elements

我想檢查某個列中的所有元素是否都包含數字 0?

我有一個使用df=pd.read_table('ad-data')讀取的數據集
從這里我感覺到了一個帶有元素的數據框

[0] [1.] [2] [3] [4] [5] [6] [7] ....1559

[1.]  3   2   3   0   0   0   0

[2]  2   3   2   0   0   0   0

[3]  3   2   2   0   0   0   0

[4]  6   7   3   0   0   0   0

[5]  3   2   1   0   0   0   0

...
3220

我想檢查從第 4 列到 1559 的數據集是否只包含 0 或其他值。

在此處輸入圖像描述

您可以使用 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM