2

I have a Pandas data frame like this one

String = ["".join(np.random.choice(list("PQRSTUVXYZ"), size=7)) for _ in range(7)]
Position = np.random.randint(2,7, size = 7)
df=pd.DataFrame((String,Position)).T

I would like to apply the lower() function JUST in the letter which the index is column Position.

I've tried:

df = df[0][df[1]].str.lower()

But it is lowering the whole string.

Thanks for your help!

2 Answers 2

3

here is a list comprehension with slice and slice_replace:

df['new'] = ([df[0].str.slice_replace(
             i,i+1,df[0].str.slice(i,i+1).iloc[e].lower()).iloc[e] 
             for e,i in enumerate(df[1])])

         0  1      new
0  TZPVTRT  2  TZpVTRT
1  VSSXYUP  3  VSSxYUP
2  YUTXTQS  2  YUtXTQS
3  SZRURSU  5  SZRURsU
4  XRXQVUP  3  XRXqVUP
5  PSQZZVV  6  PSQZZVv
6  XYYXPYV  3  XYYxPYV

note if your index starts from 1 and not 0 , replace df[0].str.slice(i,i+1) with df[0].str.slice(i-1,i)

Sign up to request clarification or add additional context in comments.

Comments

2

You can index the strings. Index up to the lower character, turn that character to lower, and then add everything left over. Really nothing too different from using Series.str.slice_replace, but perhaps a bit more readable.

df['new_str'] = [s[:i] + s[i].lower() + s[i+1:] for s,i in zip(df[0], df[1])]

         0  1  new_str
0  TTTQTYT  3  TTTqTYT
1  USRRUZS  2  USrRUZS
2  PPXQZZT  6  PPXQZZt
3  UZZVQRQ  3  UZZvQRQ
4  ZVUQPUV  6  ZVUQPUv
5  TRPPSVU  5  TRPPSvU
6  YYZPURQ  5  YYZPUrQ

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.