How to add string at the beginning of each row?

Question:

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

Asked By: Kas

||

Answers:

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
Answered By: jezrael

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
Answered By: mozway
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.