7

I have a CSV that I'm needing to create a column of random unique MongoDB ids in python.

Here's my csv file:

   import pandas as pd

   df = pd.read_csv('file.csv', sep=';')
   print(df)

        Zone
        Zone_1
        Zone_2

I'm currently using this line of code to generate a unique ObjectId - UPDATE

import bson

x = bson.objectid.ObjectId()
df['objectids'] = x
print(df)

Zone; objectids
Zone_1; 5bce2e42f6738f20cc12518d
Zone_2; 5bce2e42f6738f20cc12518d

How can I get the ObjectId to be unique for each row?

mm_nieder
  • 431
  • 1
  • 4
  • 10
  • Possible duplicate of [Adding new column to existing DataFrame in Python pandas](https://stackoverflow.com/questions/12555323/adding-new-column-to-existing-dataframe-in-python-pandas) – mattdonders Oct 22 '18 at 20:46
  • Hi @mattdonders, thank you for your response. This is close, I now created a `ObjectId` column in `df`, but none of the ids are unique, they're all the same id... Please see my update. – mm_nieder Oct 22 '18 at 20:56

1 Answers1

9

Hate to see you down voted... stack overflow goes nuts with the duplicate question nonsense, refuses to provide useful assistance, then down votes you for having the courage to ask about something you don't know.

The referenced question clearly has nothing to do with ObjectIds, let alone adding them (or any other object not internal to NumPy or Pandas) into data frames.

You probably need to use a map

this assumes the column "objectids" is not a Series in your frame and "Zone" is a Series in your frame

df['objectids'] = df['Zone'].map(lambda x: bson.objectid.ObjectId())

Maps are super helpful (though slow) way to poke every record in your series and particularly helpful as an initial method to connect external functions.

https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.map.html

bauman.space
  • 1,993
  • 13
  • 15
  • YES! Thank you so much. I'm new to pymongo so I wasn't quite sure how to word some of the question. Thank you so much for your helpful answer! – mm_nieder Oct 24 '18 at 14:11