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

Sunday, August 7, 2022

[FIXED] How to truncate two columns of decimal points in a python pandas dataframe?

 August 07, 2022     dataframe, decimal, pandas, python     No comments   

Issue

I need help with truncating columns of decimals within a dataframe, that ties in with other calcuations to output a 1 or 0 binary column called "scenario1". Said dataframe has 20+ columns.

In this case I have two columns (columns A and columns B) of decimals along a time-based index. The columns may have varied amount of decimal points, and have NaN values in earlier rows.

I'm trying to truncate values in ONLY these two columns for use in a calculation and "throw away", WITHOUT changing the original columns or generating new columns.

e.g. ColA can be 4 decimals, ColB can be 6 decimals.

ColA ColB
NaN NaN
NaN NaN
0.9954 0.995642
0.9854 0.997450

If the value of ColA and ColB is close enough, I want to output TRUE. To do that, I have to somehow truncate both ColA and ColB to one decimal place without any rounding up or down. So it becomes the following:

ColA ColB
NaN NaN
NaN NaN
0.9 0.9
0.9 0.9

I need this truncation to happen within a function "scenario1", trying to have the code be efficient as possible. My current failed attempts are those lines with math.trunc(1000 * df.tenkan)/1000. This is from another post here, 3rd solution.:

def scenario1(df):
    df.loc[:, ('scenario1')] = np.where((df.close <= 2) & (df.tenkan > df.tenkan.shift(1)) &
     (df.kijun > df.kijun.shift(1)) & 
    ((math.trunc(1000 * df.tenkan) / 1000) == (math.trunc(1000 * df.kijun) / 1000)) & 
    (df.span_a > df.span_a.shift(1)) & (df.span_b > df.span_b.shift(1)) & 
    ((math.trunc(1000 * df.span_a) / 1000) == (math.trunc(1000 * df.span_b) / 1000)) & 
    (df.volume <= 300000), 1, 0)

    return df

But I got the following error: TypeError: type Series doesn't define trunc method

Any ideas how I can do this?

Screenshot of the actual dataframe below: enter image description here


Solution

You can use numpy trunc:

df = pd.DataFrame({'ColA ': [0.9954, 0.9854], 'ColB': [0.995642, 0.99745]})

np.trunc(10 * df) / 10

Result:

   ColA   ColB
0    0.9   0.9
1    0.9   0.9


Answered By - Stef
Answer Checked By - David Marino (PHPFixing Volunteer)
  • 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