How to Read Tsv File in Python


To read a TSV file with pandas in Python, you can utilise the following basic syntax:

            df = pd.read_csv("information.txt", sep="\t")                      

This tutorial provides several examples of how to use this function in practice.

Read a TSV File with a Header

Suppose nosotros take the following TSV file chosen data.txt with a header:

To read this file into a pandas DataFrame, we can use the following syntax:

                                                            import                  pandas                  every bit                  pd                #read TSV file into pandas DataFrame              df = pd.read_csv("data.txt", sep="\t")              #view DataFrame              impress(df)  	column1	column2 0	i	four ane	3	4 2	two	5 3	7	9 4	9	1 five	6	3 6	v	7 7	8	eight 8	3	1 9	4	ix                      

We can print the class of the DataFrame and discover the number of rows and columns using the following syntax:

                          #display grade of DataFrame                            print(type(df))  <class 'pandas.core.frame.DataFrame'>              #brandish number of rows and columns in DataFrame                df.shape                                (10, 2)                                                    

We can meet thatdf is a pandas DataFrame with 10 rows and ii columns.

Read a TSV File with No Header

Suppose nosotros have the following TSV file chosen data.txt with no headers:

To read this file into a pandas DataFrame, we can use the post-obit syntax:

                          #read TSV file into pandas DataFrame              df = pd.read_csv("data.txt", sep="\t", header=None)              #view DataFrame              print(df)          0	1 0	one	four i	3	four 2	2	5 3	7	9 4	9	one 5	six	iii 6	5	7 7	viii	8 viii	iii	1 nine	4	9                      

Since the text file had no headers, pandas simply named the columns 0 andi.

Read TSV File with No Header & Specify Cavalcade Names

If we'd like, we can assign column names while importing the text file by using thenames argument:

                          #read TSV file into pandas DataFrame and specify column names              df = pd.read_csv("data.txt", sep="\t", header=None,                names=["A", "B"]              )              #display DataFrame                            print(df)  	A	B 0	one	iv one	iii	iv 2	ii	v 3	seven	ix 4	9	ane 5	6	3 6	five	7 seven	8	viii 8	three	ane 9	4	9                      

Additional Resources

The following tutorials explain how to read other types of files with pandas:

How to Read Text File with Pandas
How to Read CSV Files with Pandas
How to Read Excel Files with Pandas
How to Read a JSON File with Pandas

shawfainjusly.blogspot.com

Source: https://www.statology.org/pandas-read-tsv/

Artikel Terkait

Belum ada Komentar untuk "How to Read Tsv File in Python"

Posting Komentar

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel