Kingua Kingua - 3 months ago 9
Python Question

How can I replace Python Pandas table text values with unique IDs?

I am using Pandas to read a file in this format:

fp = pandas.read_table("Measurements.txt")
fp.head()

"Aaron", 3, 5, 7
"Aaron", 3, 6, 9
"Aaron", 3, 6, 10
"Brave", 4, 6, 0
"Brave", 3, 6, 1


I want to replace each name with a unique ID so output looks like:

"1", 3, 5, 7
"1", 3, 6, 9
"1", 3, 6, 10
"2", 4, 6, 0
"2", 3, 6, 1


How can I do that?

Thanks!

Answer

It looks like this Replace all occurrences of a string in a pandas dataframe might hold your answer. According to the documentation, pandas.read_table creates a dataframe and a dataframe has a replace function.

fp.replace({'Aaron': '1'}, regex=True)

Although you probably don't need to have the regex=True part as it's a direct replacement in full.

Comments