简体   繁体   中英

How do I remove square brackets for all the values in a column?

I have a column named keywords in my pandas dataset. The values of the column are like this:

[jdhdhsn, cultuere, jdhdy]

I want my output to be

jdhdhsn, cultuere, jdhdy

Try this

keywords = [jdhdhsn, cultuere, jdhdy]
if(isinstance(keyword, list)):
    output = ','.join(keywords)
else:
    output = keywords[1:-1]

The column of your dataframe seems to be a list

Lists are formatted with brackets and each elements of that list's repr ()

Pandas has built in functions for dealing with strings

df['column_name'].str let's you use each element in the column and apply a str function on them. Just like ', '.join(['foo', 'bar', 'baz'])

Thus df['column_name_str'] = df['column_name'].str.join(', ') will produce a new column with the formatting you're after.

You can also use the .apply to perform arbitrary lambda functions on a column, such as:

df['column_name'].apply(lambda row: ', '.join(row))

But since pandas has the .str built in this isn't needed for this example.

Try this

data = ["[jdhdhsn, cultuere, jdhdy]"]
df = pd.DataFrame(data, columns = ["keywords"])
new_df = df['keywords'].str[1:-1]
print(df)
print(new_df)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM