Iterate over some columns in a data frame

Hi, I have a data frame like this:

Ticker P/EP/SP/BP/FCF Dividend No. 1 NTCT 457.32 3.03 1.44 26.04 - 2 GWRE 416.06 9.80 5.33 45.62 - 3 PEGA 129.02 4.41 9.85 285.10 0.28% 4 BLKB 87.68 4.96 14.36 41.81 0.62% 

First, I want to convert the values ​​to columns that contain numbers (which are currently strings) for float values. So here I would have 4 middle columns that require conversion to float. Will a simple loop work with this case?

Secondly, the problem with the last column is 'Dividend' , where there is a percentage value as a row. In fact, I can convert it to decimal numbers, however I was wondering if there was a way to save%, and the values ​​would still be computed.

Any ideas for these two issues?

+5
source share
2 answers

plan

  • Take out the 'Ticker' because it is not numeric.
  • use assign to overwrite Dividend by dividing %
  • use apply with pd.to_numeric to convert all columns
  • use eval to get Dividend in the correct decimal space


 df[['Ticker']].join( df.assign( Dividend=df.Dividend.str.strip('%') ).drop('Ticker', 1).apply( pd.to_numeric, errors='coerce' ) ).eval('Dividend = Dividend / 100', inplace=False) Ticker P/EP/SP/BP/FCF Dividend No. 1 NTCT 457.32 3.03 1.44 26.04 NaN 2 GWRE 416.06 9.80 5.33 45.62 NaN 3 PEGA 129.02 4.41 9.85 285.10 0.0028 4 BLKB 87.68 4.96 14.36 41.81 0.0062 

more lines
more readable

 nums = df.drop('Ticker', 1).assign(Dividend=df.Dividend.str.strip('%')) nums = nums.apply(pd.to_numeric, errors='coerce') nums = nums.assign(Dividend=nums.Dividend / 100) df[['Ticker']].join(nums) Ticker P/EP/SP/BP/FCF Dividend No. 1 NTCT 457.32 3.03 1.44 26.04 NaN 2 GWRE 416.06 9.80 5.33 45.62 NaN 3 PEGA 129.02 4.41 9.85 285.10 0.0028 4 BLKB 87.68 4.96 14.36 41.81 0.0062 
+2
source

Assuming all P/... columns contain the correct numbers:

 In [47]: df.assign(Dividend=pd.to_numeric(df.Dividend.str.replace(r'\%',''), errors='coerce') ...: .div(100)) \ ...: .set_index('Ticker', append=True) \ ...: .astype('float') \ ...: .reset_index('Ticker') ...: Out[47]: Ticker P/EP/SP/BP/FCF Dividend No. 1 NTCT 457.32 3.03 1.44 26.04 NaN 2 GWRE 416.06 9.80 5.33 45.62 NaN 3 PEGA 129.02 4.41 9.85 285.10 0.0028 4 BLKB 87.68 4.96 14.36 41.81 0.0062 
+1
source

Source: https://habr.com/ru/post/1266490/


All Articles