-1

Using Python, Pandas, I have a couple columns that have lists in them, I want to convert the list to a string.

Example:I have the following values in a record, in the field ev_connector_types

[u'ACME', u'QUICK_CONNECT'] I'd like the value for that record to show: ACME, QUICK_CONNECT, without the list brackets, the 'u', and the quotes.

I've tried.

df.loc[df["ev_connector_types"].isnull(), "ev_connector_types"] = ", ".join(df["ev_connector_types"])
df["ev_connector_types"] = df["ev_connector_types"].agg(' '.join)
df["ev_connector_types"] = df["ev_connector_types"].apply(''.join)
df["ev_connector_types"] = df["ev_connector_types"].str.join(" ")

But I'm not getting anywhere.

Basically do this:

myList = [u'ACME', u'QUICK_CONNECT'] 
x = " ".join(myList) 

Within Pandas.

After much trial and error, I found my field value was just a bunch of string characters like "[u'ACME', u'QUICK_CONNECT']" and the join was doing this: [ u' A C M E ' , u ' Q U I C K _ C O N N E C T ' ] If I split it on the comma, I got a list and the answer below worked. However I ended up doing a lsplit and rsplit and a replace to get what I wanted.

This line was the problem, it took the field type from a list to a string: df["ev_connector_types"] = df["ev_connector_types"].astype('str')

Bill Chappell
  • 281
  • 4
  • 20
  • Don't know if this is the root cause, but you're certainly using an unsupported python version – inspectorG4dget Feb 01 '21 at 22:34
  • Please have a look at [How to make good pandas examples](https://stackoverflow.com/questions/20109391/how-to-make-good-reproducible-pandas-examples) and provide a [mcve] so that we can better understand how to help you – G. Anderson Feb 01 '21 at 22:39
  • Does this answer your question? [Column of lists, convert list to string as a new column](https://stackoverflow.com/questions/45306988/column-of-lists-convert-list-to-string-as-a-new-column) – noah Feb 01 '21 at 22:59

1 Answers1

2

It's as simple as you have stated. Just do within apply()

import pandas as pd
df = pd.DataFrame([{"ev_connector_types":[u'ACME', u'QUICK_CONNECT']}])

df.assign(ev_connector_types=df["ev_connector_types"].apply(lambda l: " ".join(l)))
Rob Raymond
  • 29,118
  • 3
  • 14
  • 30