Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reading a text file using Pandas accurately in Python

I am trying to read B.txt using pandas. It prints the value of B but not as a list. I present the current and expected outputs.

import pandas as pd

df = pd.read_csv("B.txt", header=None)
B = df. to_numpy()
B=B.tolist()
print("B =",B)

The current output is

B = [['B=3']]

The expected output is

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

B=[3]

>Solution :

Add squeeze = True for Series, so ouput is B = ['B=3'], select first value and split, select second value and convert to int:

s  = pd.read_csv("B.txt", header=None, squeeze = True)
print (s)
0    B=3
Name: 0, dtype: object

print (s.iat[0])
B=3
print (s.iat[0].split('='))
['B', '3']

print (s.iat[0].split('=')[1])
3

print("B =", int(s.iat[0].split('=')[1]))
B = 3
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading