0

How do i create a pandas column, where the lists inside my list become cells on their own? E.g.: I have the following nested list:

nested = [['1', '2', '3'],['2', '3', '1'],['3', '4'],['1']]

This list contains around 300 separate lists with strings of different length (min 1 max 5). Now i want to create a pandas dataframe column, where each of these lists in a single cell, not where each string is in a different cell. I tried it this way

df['new column'] = df[["col1", "col2"]].apply(lambda x: ''.join(x), axis=1)

but it gives me an error messsage, because there are some None values, because the lists initially had different lengths.

4
  • 1
    Could you be clearer about the expected output? Commented Feb 13, 2019 at 21:26
  • 1
    pd.DataFrame([nested]).T or more likely df['new_column'] = pd.Series(nested)? Commented Feb 13, 2019 at 21:27
  • The output should look like this: Dataframe with one column, each cell represents one list e.g. ['1', '2', '3',] is first cell, then ['2', '3', '1'] is second cell.. Commented Feb 13, 2019 at 21:33
  • Thanks AChampion it worked! Commented Feb 13, 2019 at 21:35

1 Answer 1

3

If I understood correctly this will be enough:

import pandas as pd

nested = [['1', '2', '3'], ['2', '3', '1'], ['3', '4'], ['1']]
df = pd.DataFrame({'col1': nested})
print(df)

Output

        col1
0  [1, 2, 3]
1  [2, 3, 1]
2     [3, 4]
3        [1]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.