Home > Software design >  How to rename rows in a column with pandas?
How to rename rows in a column with pandas?

Time:10-03

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

CodePudding user response:

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")*** 

CodePudding user response:

df = df.<your_column_name>.replace(to_replace='new york', value='NY')

CodePudding user response:

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
  • Related