Home > Back-end >  How to add string at the beginning of each row?
How to add string at the beginning of each row?

Time:11-23

I would like to add a string at the beginning of each row- either positive or negative - depending on the value in the columns: enter image description here

I keep getting ValueError, as per screenshot

CodePudding user response:

For a generic method to handle any number of columns, use pandas.from_dummies:

cols = ['positive', 'negative']

user_input_1.index = (pd.from_dummies(user_input_1[cols]).squeeze()
                       '_' user_input_1.index
                      )

Example input:

   Score  positive  negative
A      1         1         0
B      2         0         1
C      3         1         0

Output:

            Score  positive  negative
positive_A      1         1         0
negative_B      2         0         1
positive_C      3         1         0

CodePudding user response:

Use Series.map for prefixes by conditions and add to index:

df.index = df['positive'].eq(1).map({True:'positive_', False:'negative_'})   df.index

Or use numpy.where:

df.index = np.where(df['positive'].eq(1), 'positive_','negative_')   df.index
  • Related