How to rename rows in a column with pandas?

Question:

I have 2 merged csv datasets and I need to rename the rows putting only the abbreviation, like "new york" becomes "NY".

Asked By: oioi

||

Answers:

df = df.<your_column_name>.replace(to_replace='new york', value='NY')
Answered By: Konrad Sloniewski

You can scrape a table that has the conversion and merge:

df = pd.read_html("https://abbreviations.yourdictionary.com/articles/state-abbrev.html")[0]
df = df.rename(columns=df.iloc[0]).drop(df.index[0])[["State Name", "USPS Abbreviation"]]

data = {
    "States": ["Alabama", "New York", "Kansas"],
    "Number": [1, 2, 3]
}
df2 = pd.DataFrame(data)


final_df = pd.merge(df, df2, left_on="State Name", right_on="States").drop(columns="States")

print(final_df)

  State Name USPS Abbreviation  Number
0    Alabama                AL       1
1     Kansas                KS       3
2   New York                NY       2
Answered By: Jason Baker
df.rename(columns={"<old_col_name>": "<new_col_name>"}, inplace= True)

don’t forget to add inplace=True to update the changes right away, or you can write it like

df = df.rename(columns={"<old_col_name>": "<new_col_name>"})

misread at first
this is how

***df["<col_name>"] = df["<col_name>"].replace("New York", "NY")*** 
Answered By: Mahmoud Abdelaziz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.