Splitting string value in given column (Pandas)

Viewed 26

I have a dataframe with many rows like this:

ID Variable
1 A1_1 - Red
2 A1_2 - Blue
3 A1_3 - Yellow

I'm trying to iterate over all rows so that all the 2nd column's values change to just "A1". The code I've come up with is:

for row in df.iterrows():

  current_response_id=row[1][0]

  columncount=0

  for columncount in range(2):

    variable=row[1][1];

    row[1][1]=variable.split("_")[0].split(" -")[0]

    variable=row[1][1];

However, this isn't achieving the desired result. How could I go about this?

1 Answers

Try:

df["Variable"] = df["Variable"].str.split("_").str[0]
print(df)

Prints:

   ID Variable
0   1       A1
1   2       A1
2   3       A1
Related