python编码及类型转换

使用chardet模块来判断数据的编码;输入参数为str类型。

#coding:utf-8
import chardet
f =open('hadoop.txt','r')     #打开文本文件,只读
about=f.read()         #读取文本内容
print cchardet.detect(about)       #判断字符串编码

#将字符串的原编码先转成unicode编码,再转成utf-8编码 print about.decode('gbk').encode('utf-8')

pd.DataFrame数据类型转换

# -*- coding: UTF-8 -*-
import pandas as pd
df = pd.DataFrame([{'col1':'a', 'col2':'1'}, {'col1':'b', 'col2':'2'}])
print df
print '查看df对象数据类型'
print df.dtypes
df['col2'] = df['col2'].astype('int')
print '-------------------------------------------'
print df['col2'] .dtypes

df['col2'] = df['col2'].astype('float64')
print '-------------------------------------------'
print df.dtypes

当然方法还有很多。。。

原文地址:https://www.cnblogs.com/lanchang/p/6884052.html