![](https://crypto4nerd.com/wp-content/uploads/2023/06/0ZAybJS7iKCS7o2kh.png)
For example, a file data.txt with the following content:
1, 1.3, 0.6
2, 2.1, 0.7
3, 4.8, 0.8
4, 3.3, 0.9
can be read in and displayed with
In [9]: data = np.loadtxt('data.txt', delimiter=',')
In [10]: data
Out[10]:
array([[ 1. , 1.3, 0.6],
[ 2. , 2.1, 0.7],
[ 3. , 4.8, 0.8],
[ 4. , 3.3, 0.9]])
where data is a numpy array. Without the flag delimiter= ’ , ’ , the function np.loadtxt crashes. An alternative way to read in these data is with
In [11]: df = pd.read_csv('data.txt', header=None)
In [12]: df
Out[12]:
0 1 2
0 1 1.3 0.6
1 2 2.1 0.7
2 3 4.8 0.8
3 4 3.3 0.9
where df is a pandas DataFrame. Note that the pandas function pd.read_csv already recognizes the first column as integer, whereas the second and third columns are correctly identified as float. Without the flag header=None, the entries of the first row are falsely interpreted as the column labels as shown in the next step:
In [13]: df = pd.read_csv('data.txt') # Warning:
# Incorrect result!
In [14]: df
Out[14]:
1 1.3 0.6
0 2 2.1 0.7
1 3 4.8 0.8
2 4 3.3 0.9