1

I have a dataframe as follows:

Original dataframe:

Index Value
0 aT 1
1 bee 2
2 cT 3
3 Y 4
4 D 5

I would like to combine each item in the "index" column (except items trailing with T), hyphen (-) and row number like this:

Expected result:

Index Value
0 aT 1
1 bee-1 2
2 cT 3
3 Y-3 4
4 D-4 5

My code is the following:

df = pandas.DataFrame({"Index": ["aT", "bee", "cT","Y","D"], "Value": [1, 2, 3,4,5]})
ind_name = df.iloc[df.index,0].apply(lambda x: x + '-' + str(df.index) if "T" not in x else x)

How to correct my code?

3 Answers 3

2

One way using pandas.Series.str.endswith and str.cat:

s = df["Index"]
df["Index"] = s.where(s.str.endswith("T"), 
                      s.str.cat(df.index.astype(str), "-"))
print(df)

Output:

   Index  Value
0     aT      1
1  bee-1      2
2     cT      3
3    Y-3      4
4    D-4      5
Sign up to request clarification or add additional context in comments.

Comments

0

Solution with .apply:

import pandas as pd

df = pd.DataFrame({"Index": ["aT", "bee", "cT", "Y", "D"], "Value": [1, 2, 3, 4, 5]})
df['Index'] = df.apply(lambda x: x['Index'] + ('' if 'T' in x['Index'] else f'-{x.name}'), axis=1)
print(df)

Prints:

   Index  Value
0     aT      1
1  bee-1      2
2     cT      3
3    Y-3      4
4    D-4      5

Comments

0

Try with loc with str.contains and += instead:

>>> df.loc[~df['Index'].str.contains('T'), 'Index'] += '-' + df.index.to_series().astype(str)
>>> df
   Index  Value
0     aT      1
1  bee-1      2
2     cT      3
3    Y-3      4
4    D-4      5
>>> 

Remember to add to_series() so that pandas would be able to detect corresponding indexes and add to them, just a pure Index object does not have an index since it's values are the index :)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.