Reputation: 10051
Given a small dataset df
which copied from an excel file as follows, I need to check if there Unnamed columns inside
:
id floor Unnamed: 2 type
0 1 13 NaN office
1 2 12 NaN office
2 3 9 NaN office
3 4 9 NaN office
4 5 7 NaN office
5 6 6 NaN office
6 7 9 NaN office
7 8 5 NaN office
8 9 5 NaN office
9 10 5 NaN office
10 11 4 NaN retail
Code:
lst = list(df.columns)
for x in lst:
if 'Unnamed' in x:
print('Unamed columns found')
else:
print('Normal')
Out:
Normal
Normal
Unamed columns found
Normal
In fact, when there are unamed columns, I want return Unamed columns found
, otherwise returns Normal
, which may need to modify the code like:
'Unamed columns found' if df1.columns.str.contains('^Unnamed') else 'Normal'
[x for x in df1.columns[df1.columns.str.contains('^Unnamed')]]
How could I modify the code above? Please note it's not necessary to loop and return multiple Normal
.
Thanks a lot for your help at advance.
Upvotes: 2
Views: 1238
Reputation: 25259
As you said in comment, try f-string
s = f'''{'Unnamed columns were found in your dataset'
if df.columns.str.contains('^Unnamed:').any() else 'normal'}'''
In [96]: print(s)
Unnamed columns were found in your dataset
If you want number as in the comment, try this
m = df.columns.str.contains('^Unnamed:')
s = f'''{str(m.sum()) + ' Unnamed columns were found in your dataset'
if m.any() else 'normal'}'''
In [140]: s
Out[140]: '1 Unnamed columns were found in your dataset'
Upvotes: 2