PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 27, 2022

[FIXED] How to keep n characters of each row of a pd df, where n differs by row?

 April 27, 2022     pandas, python, split, warnings     No comments   

Issue

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!


Solution

Try with apply:

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

>>> df
   lenght String
0      -3    def
1      -5  hijkl


Answered By - not_speshal
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing