Home > OS >  Removing a comma at end a each row in python
Removing a comma at end a each row in python

Time:12-02

I have the below dataframe

enter image description here

After doing the below manipulations to the dataframe, I am getting the output in the Rule column with comma at the end which is expected .but I want to remove it .How to do it

df['Rule'] = df.State.apply(lambda x: str("'" str(x) "',"))
df['Rule'] = df.groupby(['Description'])['Rule'].transform(lambda x: ' '.join(x))
df1 = df.drop_duplicates('Description',keep = 'first')
df1['Rule'] = df1['Rule'].apply(lambda x: str("(" str(x) ")")

I have tried it using ilo[-1].replace(",",""). But it is not working .

CodePudding user response:

You can use a strip method, in this case it would be rstrip to strip from the right-side (end of string)

df["Rule"] = df["Rule"].str.rstrip(",")

CodePudding user response:

Try this:

df['Rule'] = df.State.apply(lambda x: str("'" str(x) "'"))
df['Rule'] = df.groupby(['Description'])['Rule'].transform(lambda x: ', '.join(x))
df1 = df.drop_duplicates('Description', keep = 'first')
df1['Rule'] = df1['Rule'].apply(lambda x: str("(" str(x) ")"))
  • Related