python-3.xcsvbinaryfilesfile-writingcsvwriter

python program to generate a csv file where each column is a data of sinusoidal wave


The requirement is to generate a csv file where each column is a data of sinusoidal wave of frequency 1 Hz,2 Hz, 3Hz, 4Hz, 5Hz, 6Hz, 7Hz. Thus total 7 columns.

100 wave points for 1Hertz and thus total 100 x 7= 700 points.

Can anyone explain how to code for this requirement


Solution

  • You can try this. Here,

    1. I'm using Numpy to get required values for the frequency.
    2. Then copy these values to pandas dataframe
    3. And finally write it to csv file.

    Please refer this link for further useful details regarding sine waves in Python

    import numpy as np
    import pandas as pd    
    
    def get_values_for_frequency(freq):
        # sampling rate
        sr = 100.0
        # sampling interval
        ts = 1.0/sr
        t = np.arange(0,1,ts)
    
        # frequency of the signal
        freq = 5   
        y = np.sin(2*np.pi*freq*t)
        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('sine.csv', index=False)
    

    Sample output from generated csv file:

    enter image description here