Home > other >  For loop values to dataframe
For loop values to dataframe

Time:07-06

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)

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!

CodePudding user response:

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.

  • Related