4

I have this code

import pandas
data = pandas.read_csv('report.csv')
data = data.drop(['date',axis=1)
data.to_csv('final_report.csv')

I would like to know if there is a way to remove the curly braces from the dictionaries. It is purely for ascetics.

I would just like: date: June

enter image description here

Randal
  • 363
  • 5
  • 21

1 Answers1

2

Since the data is from a CSV file, it is probably a string and you can just remove the curly brackets using slicing:

data['data'] = data['data'].str[1:-1]

The pandas documentation on Working with text data isn't very clear about this, but the Pandas.Series.str methods support slicing as well as indexing. There is also a Pandas.Series.str.slice() method that can be used for slicing.

The slice notation is given as [start:stop]. In your case, the brackets are the first and last characters in the string. To get rid of them, you need to take the slice starting from the second character and ending before the last character. Python uses 0-based indexing, so the start position indicating the second character is 1. Indexing from the end of a sequence is designated using negative numbers with -1 being the last character. Slices include all characters up to (but not including) the stop position, so the stop position to exclude the last character is -1. Putting this together, you need the to take a slice from the second character to the next to last character, which is expressed as [1:-1].

For a more detailed description of slicing notation in Python, take a look at this answer: https://stackoverflow.com/a/509295/7517724.

Craig
  • 4,605
  • 1
  • 18
  • 28
  • 1
    If the elements of column `data` are somehow actually dictionaries, then convert them to strings first: `df['data'] = df['data'].astype('str')` – Derek O Jul 14 '20 at 03:31
  • it looks like it was a string...this worked just fine...thank you!!! – Randal Jul 14 '20 at 03:32
  • @Craig - if you would not mind, an explanation of this is actually working would be appreciated. by looking at it I cant figure it out – Randal Jul 14 '20 at 03:34
  • @Randal are you not sure why this is a string and not a dictionary, or how the slicing operation works? – Craig Jul 14 '20 at 03:36
  • @Craig - I see you put info on where I can get more info on slice... that will help...thanks – Randal Jul 14 '20 at 04:36