Home > Software design >  Put a new column inside a Dataframe Python
Put a new column inside a Dataframe Python

Time:12-26

The Dataframe that I am working on it have a column called "Brand" that have a value called "SEAT " with the white space. I achieved to drop the white space but I don't know how to put the new column inside the previous Dataframe. I have to do this because I need to filter the previous Dataframe by "SEAT" and show these rows.

I tried this:

import pandas as pd

brand_reviewed = df_csv2.Brand.str.rstrip()

brand_correct = 'SEAT'

brand_reviewed.loc[brand_reviewed['Brand'].isin(brand_correct)]

Thank you very much!

CodePudding user response:

As far as I understand,

you're trying to return rows that match the pattern "SEAT". You are not forced to create a new column. You can directly do the following:

df2 = brand_reviewed[brand_reviewed.Brand.str.rstrip() == "SEAT"]
print(df2)

CodePudding user response:

You have done great. I will also mentioned another form on how you can clead the white spaces. And also, if you just want to add a new column in your current dataframe, just write the last line of this code.

import pandas as pd

brand_reviewed = pd.read_csv("df_csv2.csv")

data2 = data["Brand"].str.strip()

brand_reviewed["New Column"] = data2

If you have another query, let me know.

Octavio Velázquez

  • Related