一、调用pandas
- import pandas:导入pandas包,后续代码就可以使用pandas包里定义好的功能了。
- import pandas as pd:
相当于将pandas包重命名为pd,这样之后使用pandas包的功能的时候,直接写pd,而不需要写pandas,更省事。
二、打开和保存文件
(一)打开文件
1. 打开excel、csv文件
- pd.read_csv(filepath)
import pandas as pd
filepath = 'E:\\python\\test.csv'
df = pd.read_csv(filepath)
- pd.read_excel(filepath)
import pandas as pd
filepath = 'E:\\python\\test.xlsx'
df = pd.read_excel(filepath)
2. 打开json文件
- json.load
import json
with open ('filename.json','r') as openfile:
json_object = json.load(openfile)
3. 打开XML文件
python没有专门的包可以直接打开xml文件,可以parse
import pandas as pd
import xml.etree.ElementTree as etree
tree = etree.parse('filexmaple.xml')
root = tree.getroot()
columns = ['name', 'age', 'birthday']
df = pd.DataFrame(columns = columns)
for node in root:
name = node.find('name').text
age = node.find('age').text
bday = node.fine('birthday').text
可以在打开文件的时候,将第一行设置为header(即列名称)。或者可以手动添加header
- 设置第一行