Home > Net >  how to convert pandas dataframe to binary file in python
how to convert pandas dataframe to binary file in python

Time:03-04

import numpy as np
import pandas as pd
def get_values_for_frequency(freq):
    # sampling information
    Fs = 100# sample rate no of samppes per second
    T = 1/Fs # sampling period   %sample per second
    t = 1 # seconds of sampling
    N = Fs*t # total points in signal
    # signal information
    #freq = 100 # in hertz, 
    omega = 2*np.pi*freq # angular frequency for sine waves
    t_vec = np.arange(N)*T # time vector for plotting
    y = np.sin(omega*t_vec)
    return y
df = pd.DataFrame(columns =['1Hz','2Hz', '3Hz', '4Hz', '5Hz', '6Hz', '7Hz'])
df['1Hz']=pd.Series(get_values_for_frequency(1))
df['2Hz']=pd.Series(get_values_for_frequency(2))
df['3Hz']=pd.Series(get_values_for_frequency(3))
df['4Hz']=pd.Series(get_values_for_frequency(4))
df['5Hz']=pd.Series(get_values_for_frequency(5))
df['6Hz']=pd.Series(get_values_for_frequency(6))
df['7Hz']=pd.Series(get_values_for_frequency(7))
#df.to_csv('samplepersecond.csv')
ndary=df.to_records(index=False)

This is the code to generate a sine wave .Here I generated a sine wave with 7 columns(from 1 Hz to 7 Hz) and with 100 rows. Then I created a pandas Dataframe to store all these values. Now , the requirement is to convert this Dataframe into binary file with datatype of int16. So each value in a dataframe should be converted into 16 bit signed integer and then to convert into binary file

CodePudding user response:

You can convert your data frame values to int16 by using the astype function.

import numpy as np

df = df.astype(np.int16)

Then you can save your data frame in HDF5 format by using to_hdf.

df.to_hdf('tmp.hdf','df', mode='w')

  • Related