Joseph Chu's Blog

积极勤奋,主动勇敢


  • Home

  • Archives

  • Tags

  • Categories

  • About

  • Search

Pandas read_csv()参数

Posted on 2018-12-18 | Edited on 2018-12-31 | In Python Package Usage

先记录自己目前使用过的用法,后续遇到再补充

1
2
3
4
5
6
df = pd.read_csv(
path,
usecols=[0, 5], # 只选择第1列和第6列
header=None, # None: 不将第一行当做列名,0: 将第一行当做列名, 1: 将第二行当做列名
names=["target", "text"], # 指定df中的列名
)

Pandas 按照某一列的值分割Dataframe

Posted on 2018-12-18 | Edited on 2018-12-31 | In Python Package Usage

设有如下df

1
2
3
4
    target
0 1
1 2
2 3

我们希望可以将其根据target的值的不同,分为若干个子df,方法如下。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
df_1 = df[df["target"].isin(["1"])]
print(df["target"].isin(["1"]))
"""
target
0 True
1 False
2 False
"""

print(df_1)
"""
target
0 1
"""

tf.control_dependencies

Posted on 2018-12-18 | Edited on 2018-12-30 | In Python Package Usage

简单来说,tf.control_dependencies([,]) 是用来保证with下的op执行之前,先执行传入的op

tf.identify() 则是返回一个与传入tensor一模一样新的tensor的op,这会增加一个新节点到gragh中。

Read more »

Gensim加载FastText模型

Posted on 2018-12-18 | Edited on 2018-12-30 | In Python Package Usage
1
2
3
4
5
6
from gensim.models.wrappers import FastText

# for *.bin
model = FastText.load_fasttext_format('sample.bin')
# for *.vec
model = FastText.load_word2vec_format('sample.vec')
Read more »

Colab 文件操作

Posted on 2018-12-18 | Edited on 2018-12-31 | In Tools

Colab常用文件操作

  • 执行shell命令
  • 上传文件
  • 下载文件
  • 使用Google Drive上的文件
  • 载入一个Python脚本
Read more »

[CI / CD] Continuous Integration / Continuous Delivery

Posted on 2018-12-04 | Edited on 2018-12-31 | In Software Engineering

敏捷软件开发(英语:Agile software development),又称敏捷开发,是一种从1990年代开始逐渐引起广泛关注的一些新型软件开发方法,是一种应对快速变化的需求的一种软件开发能力。它们的具体名称、理念、过程、术语都不尽相同,相对于“非敏捷”,更强调程序员团队与业务专家之间的紧密协作、面对面的沟通(认为比书面的文档更有效)、频繁交付新的软件版本、紧凑而自我组织型的团队、能够很好地适应需求变化的代码编写和团队组织方法,也更注重软件开发过程中人的作用。

Read more »

Pandas中 DataFrame的使用

Posted on 2018-10-01

读取行

DataFrame读取行可以通过以下两种索引

  • 行标签索引 df.loc["one"]
  • 行号索引 df.iloc[0]

行标签索引可以在创建DataFrame的时候指定,如

1
2
3
4
5
import pandas as pd
d=[[1,2,3,4],[5,6,7,8]]
index=["one","two"]
df=pd.DataFrame(d, index=index)
print df.loc["one"]

行号索引(index)可以通过df.index来查看

1
2
3
>>> df.index
RangeIndex(start=0, stop=18, step=1) # 0~17
>>> df.iloc[0] # 获取第一行

也可以全部都用df.ix[]

1
2
df.ix[3] # 读取第三行
df.ix["three"]

读取列

1
2
3
# 两个参数,第一个类似切片,指定要获取的行
# 第二个是一个list, 指定要获取的列名
df.ix[:, ["Stations"]]

列名可以通过df.columns获取

1
2
3
4
>>> df.columns
Index(['Station', 'To Tiu Keng Leng', 'To Kwun Tong', 'To Whampoa',
'Unnamed: 4', 'Unnamed: 5', 'Unnamed: 6'],
dtype='object')

DataFrame转成list

1
2
import numpy as np
l = np.array(df).tolist()

Reference

  • pandas读取行和列

BeautifulSoup 基本使用

Posted on 2018-10-01 | Edited on 2019-01-08 | In Python Package Usage

在这里主要记录自己项目中涉及到的用法,供以后参考。

获取bs实例

要使用BeautifulSoup,首先就要构建一个BeautifulSoup类实例

  • 第一个参数:要解析的html文本,可以是str, 也可以是打开的文件句柄
  • features: 指定html解析器 (关于解析器之间的区别,请戳官方文档, “安装解析器”一节)
1
2
3
4
5
from bs4 import BeautifulSoup as Soup

soup = Soup(open(sample.html), features="lxml")
# soup = Soup('<h1>my title</h1>', features="lxml")
soup.find_all('table') # 通过实例来使用一系列强大功能

查找所需的Tag

常用方法如下

1
2
3
soup.table # 等同于 soup.find('table')
soup.find('table') # 第一个出现的table, 类型为<class 'bs4.element.Tag'>
soup.find_all('table') # 所有table

获取Tag中的文本

比如说我的html文本是<b>this is sample</b>, 我想要获得的是'this is sample'

可以通过soup.text或者soup.string属性来获得

关于text和string的区别可参考Python BeautifulSoup 中.text与.string的区别

1
2
3
4
5
>>> s = Soup('<b>this is sample</b>')
>>> type(s.b)
<class 'bs4.element.Tag'>
>>> s.b.text
'this is sample'

获取包含Tag的文本

那如果我现在想获得的就是<b>this is sample</b>呢?

如果是在iPython环境下,可以直接print()相应的Tag对象

1
2
3
>>> s = Soup('<b>this is sample</b>')
>>> print(s.b)
<b>this is sample</b>

如果是在脚本里面,则需要用到Python对象的内置方法__repr__()

在print一个对象的时候实际上调用了其__repr__()方法

1
2
3
>>> s = Soup('<b>this is sample</b>')
>>> s.b.__repr__()
'<b>this is sample</b>'

Reference

BeautifulSoup 4.2.0文档

Pandas解析html

Posted on 2018-10-01 | Edited on 2018-12-31 | In Python Package Usage

pandas可以用read_html()函数直接解析html,尤其是可以吧html中的table直接转换为Dataframe,很是方便。

比如说有table html代码如下

1
<table class="table1"> <tbody> <tr> <th colspan="1" rowspan="2">Station</th> <th colspan="2">To Tiu Keng Leng</th> <th colspan="2">To Kwun Tong</th> <th colspan="2">To Whampoa</th> </tr> <tr> <th>First Train</th> <th>Last Train</th> <th>First Train</th> <th>Last Train</th> <th>First Train</th> <th>Last Train</th> </tr> <tr> <td>Whampoa</td> <td>06:10</td> <td>00:40</td> <td>06:10</td> <td>01:00</td> <td>N/A</td> <td>N/A</td> </tr></tbody></table>

通过read_html()解析得到

1
2
3
4
import pandas as pd

# 因为会返回包含df的list
df = pd.read_html(html, header=0, encoding="utf8")[0]

Reference

  • python beautifulsoup 如何抓取不规则表格的内容

Requests 库基本用法

Posted on 2018-10-01 | Edited on 2019-01-08 | In Python Package Usage

为什么选择requests,因为它能完全胜任python自带的urllib模块,简化了不必要的功能的同时让使用更加简单。

安装

1
pip3 install requests

简单使用

首先呈上官方文档,有中文版,欢迎来啃。
下面主要介绍两种方法:get和post

  • get,就是本地向服务器索取的意思,服务器检查请求头(request headers)后,如果觉得没问题,就会返回信息给本地。
1
r = requests.get(url,**args)#返回一个Response对象,我们可以从这个对象中获取所有我们想要的信息
  • post,就是本地要向服务器提交一些数据的意思,服务器还是会检查请求头,如果提交的数据和请求头都没问题,就会返回信息给本地。
1
2
3
4
5
args = {
"a": "b",
...
}
r = requests.post(url, params=args)#也是返回Response对象

参数详解

get和post方法中有许多参数可以使用,部分参数后面会详解。

  • url:就是目标网址,接收完整(带http)的地址字符串。
  • headers:请求头,存储本地信息如浏览器版本,是一个字典。
  • data:要提交的数据,字典。
  • cookies:cookies,字典。
  • timeout:超时设置,如果服务器在指定秒数内没有应答,抛出异常,用于避免无响应连接,整形或浮点数。
  • params:为网址添加条件数据,字典。
1
2
3
payload = {'key1': 'value1', 'key2': 'value2'}
r = requests.get("http://httpbin.org/get", params=payload)
#相当于目标网址变成了http://httpbin.org/get?key2=value2&key1=value1
  • proxies:ip代理时使用,字典。

Response对象使用

从这个对象中获取所有我们想要的信息非常简单,毕竟爬虫要的数据主要就三种,html源码,图片二进制数据,json数据,Response对象一次性满足你三个愿望。

1
2
3
4
5
6
7
8
9
r.encoding = 'ISO-8859-1'    #指定r.text返回的数据类型,写在r.text之前。
r.text #默认以unicode形式返回网页内容,也就是网页源码的字符串。

r.content #以二进制形式返回网页内容,下载图片时专用。
r.json() #把网页中的json数据转成字典并将其返回。

#还有一些很少用到的方法。
r.headers #返回服务器端的headers,字典。
r.status_code #返回连接状态,200正常。

Reference

Python 从零开始爬虫(零)——爬虫思路&requests模块使用

1…345…8

Joseph Chu

一日之功很有限,不过可以积少成多
72 posts
17 categories
50 tags
© 2019 Joseph Chu
Powered by Hexo v3.6.0
|
Theme – NexT.Pisces v7.0.1