How to read a text file of dictionary to dataframe?

Viewed 82

I have a text file whose body is the followingm(line by line):

{"Age":"23", "Gender": "M", "Salary": "2300"}
{"Age":"31", "Gender": "F", "Salary": "3300"}
{"Age":"27", "Gender": "M", "Salary": "2600"}
{"Age":"43", "Gender": "F", "Salary": "5300"}

Suppose this text file is Age.txt. I would like to read this textfile as a pandas dataframe so that the output would be:

"Age"  "Gender"  "Salary"
 23      "M"      2300
 31      "F"      3300
 27      "M"      2600
 43      "F"      5300

How would I achieve it?

2 Answers

Use pd.read_json with lines=True:

df = pd.read_json("your_file.txt", lines=True)
print(df)

Prints:

   Age Gender  Salary
0   23      M    2300
1   31      F    3300
2   27      M    2600
3   43      F    5300

Here's one way:

with open('test.txt', 'r') as f:
    df = pd.DataFrame(map(eval,f.read().splitlines()))
OUTPUT:
   Age Gender  Salary
0   23      M    2300
1   31      F    3300
2   27      M    2600
3   43      F    5300
Related