types={}
for col in df.columns[0]:
if df[col].dtype == object:
print('Check values inside column')
if '!' in df[col].values :
print("\nThis value exists in Dataframe")
I have a couple of the data frames. I need to check two thigs:
- if the first column in each df is string, if so, then
- if any value inside that column starts with !. I am trying to playing around with this code, but I'm getting a key error.
CodePudding user response:
This should do the trick:
df.iloc[:, 0].astype(str).str.startswith('!').any()
This assumes that the other possible dtypes do not result in a string representation that starts with a !
, which should work in the vast majority of applications.
CodePudding user response:
try this:
col = df.columns[0]
assert df[col].dtypes == 'object'
assert df[col].str.startswith('!').any()
Example with raising error:
df = pd.DataFrame({'A': ['a','b']})
col = df.columns[0]
assert df[col].dtypes == 'object'
assert df[col].str.startswith('!').any()
# AssertionError Traceback (most recent call last)
# 2 col = df.columns[0]
# 3 assert df[col].dtypes == 'object'
# ----> 4 assert df[col].str.startswith('!').any()
# AssertionError: