Read and display data from CSV (comma separated value ) file, student.csv file.
import pandas as pd
df=pd.read_csv('C:\\data\\student.csv') # use your system path
print(df.head())
Output is here
id name class mark gender
0 1 John Deo Four 75 female
1 2 Max Ruin Three 85 male
2 3 Arnold Three 55 male
3 4 Krish Star Four 60 female
4 5 John Mike Four 60 female
Options :
df=pd.read_csv('C:\\data\\student.csv',index_col='id')
df=pd.read_csv('C:\\data\\student.csv',header=None)
Output is here
0 1 2 3 4
0 id name class mark gender
1 1 John Deo Four 75 female
2 2 Max Ruin Three 85 male
3 3 Arnold Three 55 male
4 4 Krish Star Four 60 female
In the above code the header row ( first row or 0th row ) is treated as data ( not as column headers ) .
df=pd.read_csv('C:\\data\\student.csv',header=None,skiprows=1)
Output
0 1 2 3 4
0 1 John Deo Four 75 female
1 2 Max Ruin Three 85 male
2 3 Arnold Three 55 male
3 4 Krish Star Four 60 female
4 5 John Mike Four 60 female
In above code display only 3rd and 4th columns (first column is 0th column )
df=pd.read_csv('C:\\data\\student.csv',header=None,skiprows=1,usecols=[3,4])
Output
3 4
0 75 female
1 85 male
2 55 male
3 60 female
4 60 female
my_names=['my_id','my_name','my_class','my_mark','my_gender']
df=pd.read_csv('student.csv',names=my_names)
Output
my_id my_name my_class my_mark my_gender
0 id name class mark gender
1 1 John Deo Four 75 female
2 2 Max Ruin Three 85 male
3 3 Arnold Three 55 male
4 4 Krish Star Four 60 female
To remove the original headers, use header=0
df=pd.read_csv('student.csv',names=my_names,header=0)
blank_values = ["n/a", "na", "--"]
my_data=pd.read_csv("D:\\test-na_values.csv",na_values=blank_values)
my_data['status']=my_data['name'].isnull() # new column added
print(my_data)
Download test-na_values.csv file
df=pd.read_csv(path,skiprows=6)
Output
6 Alex John Four 55 male
0 7 My John Rob Fifth 78 male
1 8 Asruid Five 85 male
2 9 Tes Qry Six 78 male
3 10 Big John Four 55 female
4 11 Ronald Six 89 female
import pandas as pd
def to_float(x):
return float(x.strip('%'))/100
#return int(float(x.strip('%'))) # as integer
df=pd.read_csv('C:\\data\\student.csv',converters={'mark':to_float})
print(df.head())
Output is here
id name class mark gender
0 1 John Deo Four 0.75 female
1 2 Max Ruin Three 0.85 male
2 3 Arnold Three 0.55 male
3 4 Krish Star Four 0.60 female
4 5 John Mike Four 0.60 female
import pandas as pd
df=pd.read_csv('C:\\data\\student.csv',chunksize=3)
for chunk in df:
print(chunk)
Output
id name class mark gender
0 1 John Deo Four 75 female
1 2 Max Ruin Three 85 male
2 3 Arnold Three 55 male
id name class mark gender
3 4 Krish Star Four 60 female
4 5 John Mike Four 60 female
5 6 Alex John Four 55 male
From large CSV file to SQLite data transfer with Progress bar by using chnksize
pd.read_csv(filepath_or_buffer,
sep=’, ‘, delimiter=None, header=’infer’,
names=None, index_col=None, usecols=None,
squeeze=False, prefix=None, mangle_dupe_cols=True,
dtype=None, engine=None, converters=None,
true_values=None, false_values=None,
skipinitialspace=False, skiprows=None,
nrows=None, na_values=None, keep_default_na=True,
na_filter=True, verbose=False,
skip_blank_lines=True, parse_dates=False,
infer_datetime_format=False, keep_date_col=False,
date_parser=None, dayfirst=False, iterator=False,
chunksize=None, compression=’infer’, thousands=None,
decimal=b’.’, lineterminator=None, quotechar='”‘,
quoting=0, escapechar=None, comment=None, encoding=None,
dialect=None, tupleize_cols=None, error_bad_lines=True,
warn_bad_lines=True, skipfooter=0, doublequote=True,
delim_whitespace=False, low_memory=True,
memory_map=False, float_precision=None)
import pandas as pd
from sqlalchemy import create_engine
engine = create_engine("mysql+mysqldb://userid:password@localhost/db_name")
sql="SELECT * FROM student "
my_data = pd.read_sql(sql,engine )
my_data.to_csv('D:\my_file.csv',index=False)
### End of storing data to CSV file ###
### Reading data from CSV file and creating table in MySQL ####
student3=pd.read_csv("D:\my_file.csv")
my_data = pd.DataFrame(data=student3)
print(my_data)
### Creating new table student3 or appending existing table
my_data.to_sql(con=engine,name='student3',if_exists='append')
read_csv() function in Pandas?read_csv() function in Pandas?read_csv() function?read_csv() function handle missing or null values in a CSV file?read_csv()?header parameter in read_csv()? How can you handle cases where the CSV file has no header?read_csv()?read_csv() function handle different data types in a CSV file?usecols parameter in read_csv()?read_csv()?read_csv() handles date and time data?read_csv()? If yes, how?index_col parameter in read_csv()?read_csv()?Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.