Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check for existence of multiple columns

Is there a more sophisticated way to check if a dataframe df contains 2 columns named Column 1 and Column 2:

if numpy.all(map(lambda c: c in df.columns, ['Column 1', 'Columns 2'])):
    do_something()
like image 862
Hendrik Wiese Avatar asked Jun 28 '16 07:06

Hendrik Wiese


People also ask

How do you check if multiple columns exist in a table SQL?

Use the COL_LENGTH system function! You basically just pass the name of the table your interested in, and the name of the column within that table you want to check. This function returns the defined length of the column in bytes, if that column exists. If the column does not exist, the function returns NULL.

How do you check multiple columns?

To select multiple columns from a table, simply separate the column names with commas! For example, this query selects two columns, name and birthdate , from the people table: SELECT name, birthdate FROM people; Sometimes, you may want to select all columns from a table.

How do I check if a column exists?

Checking Existence of the Column: For checking the existence we need to use the COL_LENGTH() function. COL_LENGTH() function returns the defined length of a column in bytes. This function can be used with the IF ELSE condition to check if the column exists or not.


1 Answers

You can use Index.isin:

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

print (df)
   A  B  C  D  E  F
0  1  4  7  1  5  7
1  2  5  8  3  3  4
2  3  6  9  5  6  3

If need check at least one value use any

cols = ['A', 'B']
print (df.columns.isin(cols).any())
True

cols = ['W', 'B']
print (df.columns.isin(cols).any())
True

cols = ['W', 'Z']
print (df.columns.isin(cols).any())
False

If need check all values:

cols = ['A', 'B', 'C','D','E','F']
print (df.columns.isin(cols).all())
True

cols = ['W', 'Z']
print (df.columns.isin(cols).all())
False
like image 148
jezrael Avatar answered Sep 27 '22 16:09

jezrael