Python Forum

Full Version: converting dataframe to int numpy array
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i have a text file with 3 lines :
1,2,3
1,2,4
1,2,5


import pandas as pd
import numpy as np
df= pd.read_fwf("sample.txt",header =None)
df= df.to_numpy()
print("df:",df)
running my code gives me a result of
df:[['1,2,3']
['1,2,4']
['1,2,5']]
how to convert it to integers?
i want the output to be
[[1,2,3]
[1,2,4]
[1,2,5]]
Use reaf_csv().
>>> import pandas as pd
>>> import numpy as np

>>> df = pd.read_csv("sample.txt", header=None, sep=',')
>>> df = df.to_numpy()
>>> df
array([[1, 2, 3],
       [1, 2, 4],
       [1, 2, 5]], dtype=int64)

>>> df[0]
array([1, 2, 3], dtype=int64)
>>> df[0][2]
3
>>> type(df[0][2])
<class 'numpy.int64'>