2

I have column which consits of values that are lists and some of them are not. I would like to get dataframe that only consists of rows(so drop non list rows) that have list values. Current DF column:

Column
["a", "b", "c"]
["a"]
a
b
["cc", "dd"]

Result:

Column
["a", "b", "c"]
["a"]
["cc", "dd"]
1
  • 2
    [row for row in df['Column'] if isinstance(row, list)] is going to be faster than using a pandas method Commented Sep 3, 2019 at 13:13

2 Answers 2

2
import pandas as pd
df = pd.DataFrame({'Column': [["a", "b", "c"],["a"], 'a','b',["cc", "dd"]]})
print(df[df.Column.apply(lambda row: type(row)==list)])

Output

      Column
0  [a, b, c]
1        [a]
4   [cc, dd]
Sign up to request clarification or add additional context in comments.

Comments

1

Use isinstance method for test lists with map and filter by boolean indexing:

df1 = df[df['Column'].map(lambda x: isinstance(x, list))]

If need output only Column and possible multiple columns in real data:

df1 = df.loc[df['Column'].map(lambda x: isinstance(x, list)), ['Column']]

Or like in comment:

df1 = pd.DataFrame({'Column': [row for row in df['Column'] if isinstance(row, list)]})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.