#coding=utf-8
import pandas as pd
#read_csv可读取csv和txt文件
df1=pd.read_csv('df.csv')
print(df1)
'''
name age sex
0 lemon 20 male
1 jack 22 male
2 json 23 fmale
'''
df2=pd.read_csv('df.txt')
print(df2)
'''
name age sex
0 lemon 20 male
1 jack 22 male
2 json 23 fmale
'''
#read_excel可读取excel文件
df3=pd.read_excel('df.xlsx')
print(df3)
'''
name age sex
0 lemon 20 male
1 jack 22 male
2 json 23 fmale
'''
#输出数据:to_excel()写入到excel文件
dicts={"name":["lemon","jack","jason"],
"age":[20,15,30],
"sex":["male","male","fmale"]
}
df=pd.DataFrame(dicts)
df.to_excel('df4.xlsx',header=False,index=False)
'''
生成df4.xlsx文件,没有行索引和列索引
20 lemon male
15 jack male
30 jason fmale
'''
df.to_excel('df4.xlsx',header=True,index=True)
'''
生成df4.xlsx文件,行索引和列索引都输出
age name sex
0 20 lemon male
1 15 jack male
2 30 jason fmale
【注】:输出excel文件时,该excel文件必须关闭,否则无法写入
'''
#输出数据:to_csv()写入到csv文件
df.to_csv('df4.csv')
'''
默认都写入行索引和列索引
,age,name,sex
0,20,lemon,male
1,15,jack,male
2,30,jason,fmale
'''
#输出成字典
print(df.to_dict())
'''
{'age': {0: 20, 1: 15, 2: 30}, 'name': {0: 'lemon', 1: 'jack', 2: 'jason'}, 'sex': {0: 'male', 1: 'male', 2: 'fmale'}}
'''
#输出数据:to_html()写入到html文件
df.to_html('df4.html')
'''
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>age</th>
<th>name</th>
<th>sex</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>20</td>
<td>lemon</td>
<td>male</td>
</tr>
<tr>
<th>1</th>
<td>15</td>
<td>jack</td>
<td>male</td>
</tr>
<tr>
<th>2</th>
<td>30</td>
<td>jason</td>
<td>fmale</td>
</tr>
</tbody>
</table>
'''
网友评论