import pandas as pd
my_dict={
'NAME':['Ravi','Raju','Alex'],
'ID':[1,2,3],'MATH':[30,40,50],
'ENGLISH':[20,30,40]
}
df=pd.DataFrame(data=my_dict)
df.to_string()
We can store the string in a file .
str1=df.to_string() # collect the string in a variable
fob=open('D:\\my_data\\my_file.txt','w') # file object
fob.write(str1) # write to file.
fob.close()
This will create a file my_file.txt with the data from DataFrame inside my_data directory of D drive.
df.to_string(columns=['NAME','ID'])
Output
' NAME ID\n0 Ravi 1\n1 Raju 2\n2 Alex 3'
df.to_string(header=['NAME1','ID2','MATH3','ENGLISH4'])
Output
' NAME1 ID2 MATH3 ENGLISH4\n0 Ravi 1 30 20\n1 Raju 2 40 30\n2 Alex 3 50 40'
df.to_string(index=False)
df.to_string(col_space=10)
df.to_string(justify='center')
import pandas as pd
from sqlalchemy import create_engine
my_conn = create_engine("mysql+mysqldb://userid:pw@localhost/my_db")
sql="SELECT * FROM student LIMIT 0,10 "
df = pd.read_sql(sql,my_conn)
df.to_string()
df=pd.read_excel("D:\\my_data\\student.xlsx") # Path of the file.
df.to_string()
We can read one csv file by using read_csv()
df=pd.read_csv("D:\\my_data\\student.csv") # change the path
df.to_string()
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.