0

I have created a df one column of which contains string values that I want to trim based on a different int value each time. Ex.: From:

length String
-3 adcdef
-5 ghijkl

I wanna get:

length String
-3 def
-5 hijkl

What I tried is the following:

for i in range(len(df.index)):
    val = df['string'].iloc[i]
    n = df['length'].iloc[i]
    df['string'].iloc[i] = val[n:]

However, I keep getting this warning:

SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame

Any ideas on how I can avoid getting it?

Thanks!

  • Please initialize `df` in your example. Make something we can copy and use. – tdelaney Sep 24 '21 at 15:37
  • 1
    `df = pd.read_clipboard(sep='\t')` works fine no @tdelaney? – Henry Ecker Sep 24 '21 at 15:38
  • @HenryEcker - No, that doesn't make it a complete running script. Sure, we can copy the text and do it ourselves. The point is that the posted example should be a running script. And that forms the basis for _tested_ solutions. – tdelaney Sep 24 '21 at 15:43
  • The advice in the pandas tag wiki, [How to provide a reproducible copy of your DataFrame with to_clipboard()](https://stackoverflow.com/q/52413246/15497888) and [How to make good reproducible pandas examples](https://stackoverflow.com/q/20109391/15497888) all advise to use a clipboard formatted text to share dataframes. – Henry Ecker Sep 24 '21 at 15:45
  • @HenryEcker - But that is counter to MRE. Its not always possible to make a minimally reproducable script, but in this case its dead simple. – tdelaney Sep 24 '21 at 15:51

1 Answers1

0

Try with apply:

df["String"] = df.apply(lambda x: x["String"][x["lenght"]:], axis=1)

>>> df
   lenght String
0      -3    def
1      -5  hijkl
not_speshal
  • 22,093
  • 2
  • 15
  • 30