Finding the column in a Pandas DataFrame that contains a list with only one element
import pandas as pd
# Example DataFrame with a column containing lists
df = pd.DataFrame({'Column1': [[1, 2], [3], [4, 5]], 'Column2': [[6, 7], [8, 9], [10]]})
# Find the column with lists of length 1
result = df.apply(lambda x: x.str.len() == 1).any()
# Get the column name(s) with lists of length 1
column_names = result[result].index.tolist()
print("Column(s) with lists of length 1:", column_names)
To find the column in a DataFrame that contains a list with only one element, where the element is equal to 'positive':
import pandas as pd
# Example DataFrame with a column containing lists
df = pd.DataFrame({'Column1': [[1, 2], [3], [4, 5]], 'Column2': [[6, 7], ['positive'], [10]]})
# Find the column with lists of length 1 and element 'positive'
result = df.apply(lambda x: (x.str.len() == 1) & (x.astype(str) == 'positive')).any()
# Get the column name(s) with lists of length 1 and element 'positive'
column_names = result[result].index.tolist()
print("Column(s) with lists of length 1 and element 'positive':", column_names)
An alternative approach to find the column in a DataFrame that contains a list with only one element, where the element is equal to 'positive':
import pandas as pd
# Example DataFrame with a column containing lists
df = pd.DataFrame({'Column1': [[1, 2], [3], [4, 5]], 'Column2': [[6, 7], ['positive'], [10]]})
# Find the column with lists of length 1 and element 'positive'
result = ((df.astype(str) == 'positive') & (df.applymap(len) == 1)).any()
# Get the column name(s) with lists of length 1 and element 'positive'
column_names = result[result].index.tolist()
print("Column(s) with lists of length 1 and element 'positive':", column_names)
Using Pandas built-in method eq()
:
import pandas as pd
# Example DataFrame with a column containing lists
df = pd.DataFrame({'Column1': [[1, 2], [3], [4, 5]], 'Column2': [[6, 7], ['positive'], [10]]})
# Find the column with lists of length 1 and element 'positive'
result = ((df.astype(str).eq('positive')) & (df.applymap(len) == 1)).any()
# Get the column name(s) with lists of length 1 and element 'positive'
column_names = result[result].index.tolist()
print("Column(s) with lists of length 1 and element 'positive':", column_names)