how do you convert a txt file with a table of values and header to a numpy 2d array?

import pandas as pd

# read file
f = open('file.txt', 'r+')
data_as_list =

# preprocess data
columns = f.pop(0).split()
# correct for Temp C
starts = columns.pop(0)
columns[0] = f'{starts} {columns[0]}'

# convert the data to floats and fill out missing data with None
def convert(s: str):
    data = list(map(float, s.split()))
    return data + [None, ] * (len(columns) - len(data)) # fill put the 
data_as_list = list(map(convert, data_as_list))

# create a dataframe
df = pd.DataFrame(data_as_list, columns = columns)

# access the entry
print(df.loc[1, '0.10'])

P.S. Just noted that you want to wrap it in a function. What should be the arguments?

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top