-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')

3

1 Answer 1

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)))

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.