Kas
Kas

Reputation: 315

How to add string at the beginning of each row?

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

Upvotes: 2

Views: 183

Answers (2)

mozway
mozway

Reputation: 260920

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

Upvotes: 2

jezrael
jezrael

Reputation: 862801

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

Upvotes: 1

Related Questions