【Python, pandas】Delete All/Any 0 Columns And Rows

プログラミング

This article is available in: 日本語

This article is a reminder of the following information regarding pandas.

  1. How to delete all 0 columns
  2. How to delete even one 0 columns
  3. How to delete all 0 rows
  4. How to delete even one 0 rows

The policy is to use python’s built-in functions, all() and any(), to identify the rows and columns, and drop to delete the corresponding rows and columns.

.

How to delete all 0 columns

import pandas as pd

df = pd.DataFrame({'A':[1,2,3],'B':[0,0,0],'C':[4,0,5],'D':[6,7,8]})

def remove_all_zero_col(df):
    df = df.copy()
    for col in df.columns:
        if (df[col] == 0).all():
            df.drop(col, axis=1, inplace=True)
    return df


print('before')
print(df)

df = remove_all_zero_col(df)

print('after')
print(df)
# Output
before
   A  B  C  D
0  1  0  4  6
1  2  0  0  7
2  3  0  5  8
after
   A  C  D
0  1  4  6
1  2  0  7
2  3  5  8

How to delete even one 0 column

import pandas as pd

df = pd.DataFrame({'A':[1,2,3],'B':[0,0,0],'C':[4,0,5],'D':[6,7,8]})

def remove_any_zero_col(df):
    df = df.copy()
    for col in df.columns:
        if (df[col] == 0).any():
            df.drop(col, axis=1, inplace=True)
    return df


print('before')
print(df)

df = remove_any_zero_col(df)

print('after')
print(df)
# Output
before
   A  B  C  D
0  1  0  4  6
1  2  0  0  7
2  3  0  5  8
after
   A  D
0  1  6
1  2  7
2  3  8

How to delete all 0 rows

import pandas as pd

df = pd.DataFrame({'A':[1,0,2,3],'B':[4,0,0,5],'C':[6,0,0,7]})

def remove_all_zero_row(df):
    df = df.copy()
    for row in df.index:
        if (df.loc[row] == 0).all():
            df.drop(row, axis=0, inplace=True)
    return df


print('before')
print(df)

df = remove_all_zero_row(df)

print('after')
print(df)
# Output
before
   A  B  C
0  1  4  6
1  0  0  0
2  2  0  0
3  3  5  7
after
   A  B  C
0  1  4  6
2  2  0  0
3  3  5  7

How to delete even one 0 rows

import pandas as pd

df = pd.DataFrame({'A':[1,0,2,3],'B':[4,0,0,5],'C':[6,0,0,7]})

def remove_any_zero_row(df):
    df = df.copy()
    for row in df.index:
        if (df.loc[row] == 0).any():
            df.drop(row, axis=0, inplace=True)
    return df


print('before')
print(df)

df = remove_any_zero_row(df)

print('after')
print(df)
# Output
before
   A  B  C
0  1  4  6
1  0  0  0
2  2  0  0
3  3  5  7
after
   A  B  C
0  1  4  6
3  3  5  7

タイトルとURLをコピーしました