0

My dataframe has many lists. When try to plot them, I found that each got a parentheses at both ends. How to remove it and convert them to a normal string.

My code:

df = 
        xdat             ydat
0   [0.5,2.2,3.4]   [4.5,9.2,1.4] 
1   [2.5,3.2,3.6]   [7.5,6.2,4.4]
2   [4.5,2.9,3.7]   [8.5,3.2,8.4]

for i,r in df.iterrows():
    print(type(r['xdat'])
    #plt.plot(r['xdat'],r['ydat'])
#plt.show()

Present output:

<class 'str'>
<class 'str'>
<class 'str'>

I found that each list got parentheses at both ends as given below when I tried to plot them. But, the original data frame has no parentheses at both ends.

'[0.5,2.2,3.4]'

So, how to remove the unwanted parentheses seen at both ends of the list?

Mainland
  • 1,600
  • 1
  • 7
  • 16

1 Answers1

0

If all your lists are flat you might do:

x = '[0.5,2.2,3.4]'
y = x.strip('[]')
print(y)  # 0.5,2.2,3.4
Daweo
  • 10,139
  • 2
  • 5
  • 10
  • Will it remove just the end `'` parentheses only ? or the list brackets as well? – Mainland Apr 27 '20 at 12:16
  • I tried this in my above code with `print(type(r['xdat'].strip('[]'))` but it still says the list as string type. – Mainland Apr 27 '20 at 12:18
  • @Mainland: `.strip` is method of `str` and it does return `str` with jettisoned leading and trailing `chars`, so `'[[5]]'.strip('[]')` result in `5`, whilst `'[1,[2],3]'.strip('[]')` result in `1,[2],3` – Daweo Apr 27 '20 at 12:22
  • Ok. Got it. Now I tried this `plt.plot(r['xact'].strip('[]'),r['yact'].strip('[]'))` but got the following error. `'Unrecognized character %c in format string' % c) ValueError: Unrecognized character 9 in format string` – Mainland Apr 27 '20 at 12:26
  • I got the following when I did the `.strip([])` answer `'0.5,2.2,3.4'`. It removed `[` but the parentheses still appear here? – Mainland Apr 27 '20 at 12:41
  • I found the answer here : https://stackoverflow.com/questions/1894269/convert-string-representation-of-list-to-list Thanks – Mainland Apr 27 '20 at 12:49