Ask Your Question
1

How can I transform a dataframe into a list that contains string elements within the list using Python?

asked 2021-07-08 11:00:00 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2022-01-10 18:00:00 +0000

woof gravatar image

Here is an example of how you can transform a pandas dataframe column into a list of strings using Python:

# Import pandas library import pandas as pd # Create a sample dataframe df = pd.DataFrame({'A': [1, 2, 3], 'B': ['a', 'b', 'c']}) # Convert dataframe to list of strings lst = df['B'].apply(str).tolist() print(lst) 

Output:

['a', 'b', 'c'] 

In the above example, we selected the column 'B' from the dataframe and applied the str function to each element in the column. Then we used the tolist method to convert the resulting pandas series to a list.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2021-07-08 11:00:00 +0000

Seen: 11 times

Last updated: Jan 10 '22