0

I have a txt file that is in the format

enter image description here

I want to load this into a data frame, with columns as headers and values as rows.

Ynjxsjmh
  • 28,441
  • 6
  • 34
  • 52

2 Answers2

1

You can use pd.read_csv with sep = " ":

df = pd.read_csv({FILE_PATH}.txt, sep=' ', header=None)
df.set_index(0).T

In your case sep turned out to be \t. Besides that manually changing some rows is a better idea. I changed Weather conditions to Weather_conditions, and Time_taken (min) to Time_taken_(min). I also skipped reading the last row that would cause too hassle:

df = pd.read_csv({FILE_PATH}.txt, sep='\t', header=None)
read_those = len(df) - 1

# We read again after learning how much rows the dataframe has, and skip
# reading the last row, note that I also add *nrows* parameter here:
df = pd.read_csv({FILE_PATH}.txt, sep='\t', header=None, nrows=read_those)
df = df[0].str.split(expand=True).set_index(0).T
Nuri Taş
  • 3,828
  • 2
  • 4
  • 22
0
import pandas as pd

df = pd.read_csv('0.txt', sep='\t', header=None)

df = df[0].str.split(n=1, expand=True)

df = df.T

df.columns = df.iloc[0]

df = df[1:]

with pd.option_context('display.max_rows', None, 'display.max_columns', None):
    print(df)
Luka Banfi
  • 111
  • 8
  • While this code may solve the question, [including an explanation](//meta.stackexchange.com/q/114762) of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please [edit] your answer to add explanations and give an indication of what limitations and assumptions apply. – Adrian Mole Aug 28 '22 at 21:08