2

I want to use https://github.com/datamade/dedupe to deduplicate some records in python. Looking at their examples

data_d = {}
for row in data:
    clean_row = [(k, preProcess(v)) for (k, v) in row.items()]
    row_id = int(row['id'])
    data_d[row_id] = dict(clean_row)

the dictionary consumes quite a lot of memory compared to e.g. a dictionary created by pandas out of a pd.Datafrmae, or even a normal pd.Dataframe.

If this format is required, how can I convert a pd.Dataframe efficiently to such a dictionary?

edit

Example what pandas generates

{'column1': {0: 1389225600000000000,
  1: 1388707200000000000,
  2: 1388707200000000000,
  3: 1389657600000000000,....

Example what dedupe expects

{'1': {column1: 1389225600000000000, column2: "ddd"},
 '2': {column1: 1111, column2: "ddd} ...}
fgregg
  • 3,173
  • 30
  • 37
Georg Heiler
  • 16,916
  • 36
  • 162
  • 292

3 Answers3

3

It appears that df.to_dict(orient='index') will produce the representation you are looking for:

import pandas

data = [[1, 2, 3], [4, 5, 6]]
columns = ['a', 'b', 'c']

df = pandas.DataFrame(data, columns=columns)

df.to_dict(orient='index')

results in

{0: {'a': 1, 'b': 2, 'c': 3}, 1: {'a': 4, 'b': 5, 'c': 6}}
chthonicdaemon
  • 19,180
  • 2
  • 52
  • 66
0

You can try something like this:

df = pd.DataFrame({'A': [1,2,3,4,5], 'B': [6,7,8,9,10]})
A   B
0  1   6
1  2   7
2  3   8
3  4   9
4  5  10

print(df.T.to_dict())
{0: {'A': 1, 'B': 6}, 1: {'A': 2, 'B': 7}, 2: {'A': 3, 'B': 8}, 3: {'A': 4, 'B': 9}, 4: {'A': 5, 'B': 10}}

This is the same output as in @chthonicdaemon answer so his answer is probably better. I am using pandas.DataFrame.T to transpose index and columns.

Joe T. Boka
  • 6,554
  • 6
  • 29
  • 48
0

A python dictionary is not required, you just need an object that allows indexing by column name. i.e. row['col_name']

So, assuming data is a pandas dataframe should just be able to do something like:

data_d = {}
for row_id, row in data.iterrows():
    data_d[row_id] = row

That said, the memory overhead of python dicts is not going to be where you have memory bottlenecks in dedupe.

fgregg
  • 3,173
  • 30
  • 37