I have a dataframe with []
I want to remove [] from the Name column
I tried this:
df['Name'] = df['Name'].str.replace("['", "")
df['Name'] = df['Name'].str.replace("']", "")
But it seems not working
I have a dataframe with []
I want to remove [] from the Name column
I tried this:
df['Name'] = df['Name'].str.replace("['", "")
df['Name'] = df['Name'].str.replace("']", "")
But it seems not working
You have an error in your code, namely the '
(single-quote) character. Tried the following:
import pandas as pd
df = pd.DataFrame.from_records(data=[
{
"Name": "[Name1]",
"ID": 1
},
{
"Name": "[Name2]",
"ID": 2
},
{
"Name": "[Name3]",
"ID": 3
}
])
print(df)
df['Name'] = df['Name'].str.replace("[", "")
df['Name'] = df['Name'].str.replace("]", "")
print(df)
which returned:
Name ID
0 [Name1] 1
1 [Name2] 2
2 [Name3] 3
/home/sawik/./playground.py:81: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not* be treated as literal strings when regex=True.
df['Name'] = df['Name'].str.replace("[", "")
/home/sawik/./playground.py:82: FutureWarning: The default value of regex will change from True to False in a future version. In addition, single character regular expressions will *not* be treated as literal strings when regex=True.
df['Name'] = df['Name'].str.replace("]", "")
Name ID
0 Name1 1
1 Name2 2
2 Name3 3
Your column consists of lists, not strings, so you can't use string operations on it. What you can (and should) do is to .join
the lists of strings into strings separated by comma.
>>> df = pd.DataFrame({'Test': [['foo', 'bar'], ['baz']]})
>>> df
Test
0 [foo, bar]
1 [baz]
>>> df.dtypes
Test object
dtype: object
>>> df['Test'] = df.Test.str.join(',')
>>> df
Test
0 foo,bar
1 baz