python学习小记

最近在学会sql脚本书写之外,对数据处理数据分析进一步学习,开始学习python语言。本篇文章用于记录学习python中心得,以便后期查询:

panda库的使用总结:

调用pandas库的方法:

import numpy as np # linear algebra
import pandas as pd # import in pandas

import os
print(os.listdir("../input"))

Pandas数据结构
Pandas有两种类型的数据结构。这些是Series和dataframe数据框。
series是一种一维标记数组,可以容纳任何数据类型的数据

mySeries = pd.Series([3,-5,7,4], index=['a','b','c','d'])

DataFrame
数据框是一个二维数据结构,它包含列。

data = {'Country' : ['Belgium', 'India', 'Brazil' ],
        'Capital': ['Brussels', 'New Delhi', 'Brassilia'],
        'Population': [1234,1234,1234]}
datas = pd.DataFrame(data, columns=['Country','Capital','Population'])
print(type(data))
print(type(datas))

创建测试对象
创建一个20行5列的随机数的数据框

pd.DataFrame(np.random.rand(20,5)) # 5 columns and 20 rows of random floats

1.os.chdir() 方法
os.chdir(path) 方法用于改变当前工作目录到指定的路径。
其中:path–要切换到的新路径。例如:path = “/tmp”
**需要用到的包:**import os, sys
os.getcwd() 查看当前的工作目录

os.chdir('/Users/mx/2021')
os.getcwd()

2.python 用于读取文件的方法

主要用到的是pandas库,可以打开CSV, Excel和SQL数据。

#读取csv
df = pd.read_csv('data.csv')
type(df)
#读取excel:
pd.read_excel('filename')
pd.to_excel('dir/dataFrame.xlsx', sheet_name='Sheet1')

Others(json、SQL、table txt、 html)

#Reads from a SQL table/database
pd.read_sql(query,connection_object)

#From a delimited txt file(like TSV)
pd.read_table(filename)

#Reads from a json formatted string, URL or file
pd.read_json(json_string)

#Parses an html URL, string or file and extracts tables to a list of dataframes
pd.read_html(url)

#Takes the contentes of your clipboard and passes it to read_table()
pd.read_clipboard()

#From a dict, keys for columns names, values for data as lists
pd.DataFrame(dict)

数据存储:

#-> Writes to a CSV file
df.to_csv(filename) 

#-> Writes to a CSV file
df.to_excel(filename) 

#-> Writes to a SQL table
df.to_sql(table_name, connection_object) 

#-> Writes to a file in JSON format
df.to_json(filename) 

#-> Saves as an HTML table
df.to_html(filename) 

#-> Writes to the clipboard
df.to_clipboard()

你可能感兴趣的:(每日一贴,python)