python学习记录

①经验一:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv(‘http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data’, header=None) # 加载Iris数据集作为DataFrame对象
X = df.iloc[:, [0, 2]].values # 取出2个特征,并把它们用Numpy数组表示
X.head()时报错:AttributeError: ‘numpy.ndarray’ object has no attribute ‘head’
原因在于:X是numpy数组格式,该格式没有head方法。待解决问题,如何把numpy数组改成能用head的形式

②经验二:
希望在jupyter上显示图像,
只输入:plt.scatter(X[:50, 0], X[:50, 1],color=‘red’, marker=‘o’, label=‘setosa’) # 前50个样本的散点图
发现out是<matplotlib.collections.PathCollection at 0x2ccaf01ef0>
,希望直接在jupyter上显示。
解决方法:在代码前加上%matplotlib inline即可。

③经验三:
代码:from sklearn import datasets
import numpy as np
from sklearn.cross_validation import train_test_split
iris = datasets.load_iris() # 由于Iris是很有名的数据集,scikit-learn已经原生自带了。
报警告:D:\ac\lib\site-packages\sklearn\cross_validation.py:41: DeprecationWarning: This module was deprecated in version 0.18 in favor of the model_selection module into which all the refactored classes and functions are moved. Also note that the interface of the new CV iterators are different from that of this module. This module will be removed in 0.20.
“This module will be removed in 0.20.”, DeprecationWarning)
解决方法:将“from sklearn.cross_validation import train_test_split”
改为“from sklearn.model_selection import train_test_split”

④经验四:读取excel数据并转化为DataFrame类型
代码:import pandas as pd
#data = xlrd.open_workbook(‘C:/Users/WFD/Desktop/邮储工作/外呼/理财15天.xls’)
data = pd.read_excel(‘C:/Users/WFD/Desktop/邮储工作/外呼/理财15天.xls’)”

*⑤经验五:str函数是Python的内置函数,它将参数转换成字符串类型,即人适合阅读的形式,以下例子是转载的。

>>> str(-23) #整数转换为字符串
'-23'
 
>>> str(1.3e2) #浮点数转换为字符串
'130.0'
 
>>> a_list = [12, '-23.1', 'Python']
>>> str(a_list)  #列表转换为字符串
"[12, '-23.1', 'Python']"
>>> str(a_list)[0]
'['
 
>>> a_tuple = (23, '9we', -8.5)
>>> str(a_tuple)  #元组转换为字符串
"(23, '9we', -8.5)"
 
>>> a_dictionary = {'Huawei':'China', 'Apple':'USA'}
>>> str(a_dictionary)  #字典转换为字符串
"{'Huawei': 'China', 'Apple': 'USA'}"
>>> str(a_dictionary)[10]
' '
 
>>> a_set = {'China', 'Japan', 'UK'}
>>> str(a_set)  #集合转换为字符串
"{'Japan', 'UK', 'China'}"

注意事项
str()函数可以将字符串类型转换为字符串,这一过程不会有任何报错,但是会产生额外的时间和空间消耗。

>>> str('asdf')
'asdf'

*⑥经验六:使用make_classification构造1000个样本,每个样本有20个feature(from 寒小阳)

#numpy科学计算工具箱
import numpy as np
#使用make_classification构造1000个样本,每个样本有20个feature
from sklearn.datasets import make_classification
X, y = make_classification(1000, n_features=20, n_informative=2, 
                           n_redundant=2, n_classes=2, random_state=0)
#存为dataframe格式
from pandas import DataFrame
df = DataFrame(np.hstack((X, y[:, None])),columns = range(20) + ["class"])

”*

⑦经验七:安装graphviz和pydotplus
https://www.cnblogs.com/yxh-amysear/p/9465280.html
打开Anaconda Prompt,输入pip install pydotplus,回车,successful.
出现GraphViz’s executables not found报错很有可能是环境变量没添加上或添加错地方。

20200509-01:DataFrame 转成 numpy.ndarray的相关问题
本来想尝试运用svm算法对数据进行分类预测,但是发现SVM中的model.fit()里面的数据必须是numpy.ndarray类型的数据,所以一开始就用numpy.ndarray(data)的数据这样会照成ValueError: sequence too large; cannot be greater than 32这个问题不好解决。后面发现通过numpy.array(data)就可以直接转成numpy.ndarray类型的数据了
————————————————
原文链接:https://blog.csdn.net/qq_35307209/article/details/90475842

20200509-02:Python取numpy数组的某几行某几列方法
C_A = c_a[[0,2]] #先取出想要的行数据
C_A = C_A[:,[2,3]] #再取出要求的列数据

*20200509-03:str函数是Python的内置函数,它将参数转换成字符串类型,即人适合阅读的形式,以下例子是转载的。

>>> type(data)
pandas.core.frame.DataFrame


#np.array(data)可以将dataframe转化为numpy.ndarray
#list(data)可得到data这个dataframe的表头即列名 
>>> import numpy
matrix = numpy.array(list(data))
matrix2 = numpy.array(data)
print(matrix)
print(matrix2)
['外呼时间' '外呼种类' '交易时间' '交易渠道' '交易笔数' '名单批次号' '时间范围' '数据推送时间'
 'Y_label' '外呼日期' '外呼time' '周几']

[['2020-04-07 17:07:26' '客户调查' 23043 ... '2020-04-07' '17' 2]
 ['2020-04-07 10:10:30' '客户调查' 23435 ... '2020-04-07' '10' 2]
 ['2020-04-07 16:26:53' '客户调查' 23202 ... '2020-04-07' '16' 2]
 ...
 ['2020-04-01 17:30:31' '客户调查' 29906 ... '2020-04-01' '17' 3]
 ['2020-04-01 17:44:29' '客户调查' 29906 ... '2020-04-01' '17' 3]
 ['2020-04-01 17:36:22' '客户调查' 26203 ... '2020-04-01' '17' 3]]

*20200509-04:python list操作 非连续。

>>> matrix.tolist()
['省份',
 '二级分行',
 '姓名',
 '客户号',
 '性别',
 '年龄',
 'Y_label',
 '外呼日期',
 '外呼time',
 '周几']
#选取list中指定不连续列
>>[i for i in matrix if i in ("年龄",'交易笔数','周几')]
['年龄', '交易笔数', '周几']

*20200515-01:train_test_split 中 stratify这个参数的意义是什么?

>>> 比单独使用train_test_split来划分数据更严谨
stratify是为了保持split前类的分布。比如有100个数据,80个属于A类,20个属于B类。如果train_test_split(... test_size=0.25, stratify = y_all), 那么split之后数据如下:
training: 75个数据,其中60个属于A类,15个属于B类。
testing: 25个数据,其中20个属于A类,5个属于B类。
用了stratify参数,training集和testing集的类的比例是 AB= 41,等同于split前的比例(8020)。通常在这种类分布不平衡的情况下会用到stratify。
这个参数sklearn的文档4中讲的不是太清楚
转载:https://www.cnblogs.com/bettyty/p/6357760.html

*20200515-02:train_test_split 中 stratify这个参数的意义是什么?

# 导入包
import numpy as np
from sklearn import model_selection
 
 
# 设置数据集
x, y = np.arange(10).reshape((5, 2)), range(5)
 
# x = array([[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]])
# y = range(0, 5)
 
 
# 切分数据,不固定随机种子(random_state)时,同样的代码,得到的训练集数据不同。
x_train0, x_test0, y_train0, y_test0 =  model_selection.train_test_split( x, y, test_size=0.33)
x_train1, x_test1, y_train1, y_test1 =  model_selection.train_test_split( x, y, test_size=0.33)
 
# x_train0 = array([[2, 3], [6, 7], [4, 5]])
# x_train1 = array([[4, 5], [8, 9], [0, 1]])
 
 
#切分数据,固定随机种子(random_state)时,同样的代码,得到的训练集数据相同。
x_train2, x_test2, y_train2, y_test2 = model_selection.train_test_split( x, y, test_size=0.33, random_state=42)
x_train3, x_test3, y_train3, y_test3 = model_selection.train_test_split( x, y, test_size=0.33, random_state=42)
 
# x_train2 = array([[4, 5], [0, 1], [6, 7]])
# x_train3 = array([[4, 5], [0, 1], [6, 7]])

*20200515-03:What are the pros and cons between get_dummies (Pandas) and OneHotEncoder (Scikit-learn)??
https://stackoverflow.com/questions/36631163/what-are-the-pros-and-cons-between-get-dummies-pandas-and-onehotencoder-sciki#

*20200519-01:知识点:取array某列的方法:ll=x_string.columns[i],然后再x_string[ll]
取array某行的方法:hh=x_string.index[i],然后再x_string[hh]-(行不能这样用)
场景是这样的,决策树不是要把每一列字符型的变成数值型吗?想自己来编码,不想使用onehot编码啥的,就想着遍历每一列,取出每一列的唯一值,然后将唯一值的index赋给该值。
思路:希望先把每一列取唯一值(使用list(x_string)或x_string.columns.tolist()均可得到array–x_string的所有去重列名),然后取出该列的x_string[tt].unique()去重值。

for i in range(len(x_string.columns.tolist())):  #这里的tolist()可省略
    tt=x_string.columns.to_list()[i]  #这里的tolist()可省略
    labels = x_string[tt].unique().tolist()
    x_string[tt] = x_string[tt].apply(lambda x: labels.index(x))

20200520-01-dataframe.values获取的是dataframe中的数据,形式为数组array

*20200520-02:知识点:希望将df的某一列由string变为数值型
思路:希望先把该列使用pd.to_numeric覆盖变为数值型:data[‘外呼time’]=pd.to_numeric(data[‘外呼time’]),然后再做处理

data['外呼time']=pd.to_numeric(data['外呼time'])
type(data['外呼time'][0])  #判断某一个值type的方法

*20200520-03:知识点:python 希望保留某些不连续的列,希望不保留某些不连续的列

x_nostring=x[['年龄','客户当前总资产','外呼日期','外呼time','周几']]
x_string=x.drop(['年龄','客户当前总资产','外呼日期','外呼time','周几'],axis=1)

*20200520-04:知识点:不同类型的唯一值的取法

#取numpy.ndarray的唯一值
np.unique(y_test_hat) 
#取pandas.core.series.Series的唯一值
data['性别'].value_counts()
data['性别'].unique()
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值