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

For loop values to dataframe

I have a question. (See at the end)

Code:

def bin_to_raw(file):
    header_len = 12
    field_names = ['time', 'count']
    for i in range(0, len(file), 12):
        data = struct.unpack('< q i', file[i:i + 12])
        for values in data:
            print(values)
    return entry_frame

Edit: data is a tuple of two elements (time and count)

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

My Output is:

637727292756170000
-343
637727292756171501
-359
637727292756173001
-358
637727292756174502
-345
637727292756176002
-366
637727292756177503
-350
637727292756179004
-355
637727292756180504
-358
..........

Output of types:

<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
<class 'int'>
.....

My Question now: How can I get all of this values in a dataframe?

Like in this format:

time count
637727292756170000 -343
637727292756171501 -359
….. ……

Thanks a lot in Advance!

>Solution :

You can define a dictionary, store the values with time as a key and count as the value and convert it to a dataframe when returning like this:

def bin_to_raw(file):
    data_dict = {}
    header_len = 12
    field_names = ['time', 'count']
    for i in range(0, len(file), 12):
        data = struct.unpack('< q i', file[i:i + 12])
        #assuming data[0] = time value and data[1] = count value
        data_dict[data[0]] = data[1]
    return pd.DataFrame(data_dict.items(), columns=['time', 'count'])

The reason for using a dictionary is that it is faster than appending rows to the dataframe each time in the for loop.

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