Search code examples
pythonpython-3.xcsvbit

Convert from KB to bit


I have csv file contain values in KB like this

8.0703125
7.401367188
8.96875
8.17578125
7.552734375
7.301757813
8.1015625
7.692382813
8.221679688
8.052734375
7.854492188
7.548828125

How can I convert these values to bits ?


Solution

  • You can read from the .csv file and convert to float then convert to bits like below:

    import csv
    
    with open("Book1.csv") as fp:
        reader = csv.reader(fp)
        next(reader, None)  # skip the headers
        data_read = [row[0] for row in reader]
    
    def KB_to_bits(x):
    #     return x*8000
        return round(x*8000,2)
    
    list(map(KB_to_bits,(map(float,data_read))))
    

    Output:

    [64562.5,
     59210.94,
     71750.0,
     65406.25,
     60421.88,
     58414.06,
     64812.5,
     61539.06,
     65773.44,
     64421.88,
     62835.94,
     60390.62]
    

    Or you can use pandas like below:

    import pandas as pd
    df = pd.read_csv('Book1.csv', header=None)  
    
    def KB_to_bits(x):
    #     return x*8000
        return round(x*8000,2)
    
    df.apply(KB_to_bits)
    

    Output:

        0
    0   64562.50
    1   59210.94
    ...
    11  60390.62