Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Writing a loop with an integer in python

I have a dataframe as such:

data = [[0xD8E3ED, 2043441], [0xF7F4EB, 912788],[0x000000,6169]]
df = pd.DataFrame(data, columns=['c_code', 'occurence'])

df

I am attempting to loop through c_code to get an integer value. The following code works to obtain the integer

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

hex_val = '0xFF9B3B'
print(int(hex_val, 0))

16751419

But when I try to loop through the column I run into an issue. I currently have this running but am just overwriting every value.

for i in range(len(df)):
    df['value'] = int((df['c_code'].iloc[i]), 0)

Ideal output would be a df with a value column that reflects the value of the c_code. The image below shows the desired format but notice that the value is the same for all rows. I believe that I need to append rows but I am unsure of how to do that

enter image description here

>Solution :

I believe that you can modify the type of your column c_code and assign this to a new column.

import pandas as pd

data = [['0xD8E3ED', 2043441], ['0xF7F4EB', 912788],['0x000000',6169]]
df = pd.DataFrame(data, columns=['c_code', 'occurence'])
df['value'] = df['c_code'].apply(int, base=16)

Also, I had to put the hexadecimal numbers as strings, if not pandas converts them to int directly.

I get this result:
enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading