0

I have feature in a dataframe that stores the class information of students like:

Student_ID  CLass
S1           5
S2           7
S3           6

How can I prefix characters like C_ before the Class for every student?

1
  • 2
    Please add what you've tried already, how you currently store the information in the dataframe. Commented Jun 29, 2021 at 18:24

3 Answers 3

1

From your question, I understood that you want to add prefix C_ to all values of class column.

If that is the case (your prefix is constant C_) , you can do something like

df['CLass'] = 'C_' + df['CLass'].astype(str)
Sign up to request clarification or add additional context in comments.

Comments

1

you can do it using the apply method of pandas dataframes like this:

import pandas as pd

df = pd.DataFrame([5, 6, 7], index = ["S1", "S2", "S3"], columns = ["Class"])
df["Class"].apply(lambda x: "C_" + str(x))

Output:

S1    C_5
S2    C_6
S3    C_7
Name: Class, dtype: object

Comments

0

It sounds like you're looking for pd.Series.apply. Typically, it can be faster to use the special string methods for Series of strings, but I can't think of an easy way to leverage those for prepending.

>>> df = pd.DataFrame({"Student_ID": ["S1", "S2", "S3"], "Class":[5,7,6]})
>>> df
  Student_ID  Class
0         S1      5
1         S2      7
2         S3      6
>>> df['Class'] = df['Class'].astype(str)
>>> df['Class'] = df['Class'].apply(lambda n: 'C_' + n)
>>> df
  Student_ID Class
0         S1   C_5
1         S2   C_7
2         S3   C_6

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.