I have a column in my dataset consisting of lists of strings like below:
column
['tablet', 'mobile', 'man']
['people', 'house']
. . .
['people', 'computer']
['computer', 'laptop']
How can I get a list of lists with the elements of this column? I want the output like this:
[['tablet', 'mobile', 'man'],['people', 'house'],. . .,['people', 'computer'],['computer', 'laptop']]
CodePudding user response:
import pandas as pd
result_list = []
df = pd.read_csv("file_name")
series_1 = df.loc[::, "column_name"]
for s in series_1:
result_list.append(s)
print(result_list)
CodePudding user response:
If you df
is like
column
0 ['tablet', 'mobile, man']
1 ['people', 'house']
2 ['people, 'computer']
3 ['computer', 'laptop']
You can get the list by calling the column with tolist()
df["column"].tolist()
Output:
[['tablet', 'mobile', 'man'], ['people', 'house'], ['people', 'computer'], ['computer', 'laptop']]
CodePudding user response:
Use ast.literal_eval
for convert strings lists in list comprehension:
import ast
L = [ast.literal_eval(x) for x in df["column"]]
print (L)
[['tablet', 'mobile', 'man'], ['people', 'house'],
['people', 'computer'], ['computer', 'laptop']]