kaggle之Python基础

基于python的kaggle练习(二)——员工离职预测 前沿 目前社会上呈现出一种公司招不到人,大批失业人员的矛盾现象,且大部分公司的离职率居高不下,很多入职没多久就辞职,所花费的培训招聘等资源都浪费了。为了弄清楚公司员工离职原因,通过kaggle上某一家企业员工离职的真实数据来对离职率进行分析建模。 一、初识数据 1、数据来源 数据来源:[https://www.kaggle.com/jiangzuo/hr-comma-sep/version/1] 2、载入数据 import pandas as pd import numpy as np data=p 阅读详情

Python基础 完结



前言

kaggle先导课程


一、语法 赋值

1.课程内容

spam_amount = 0
print(spam_amount)

# Ordering Spam, egg, Spam, Spam, bacon and Spam (4 more servings of Spam)
spam_amount = spam_amount + 4

if spam_amount > 0:
    print("But I don't want ANY spam!")

viking_song = "Spam " * spam_amount
print(viking_song)

分析:

  1. spam_amount = 0
    在声明变量前,不需要告知该变量类型,且声明后也可以直接改变其类型
  2. print(spam_amount)
    print是Python的函数,在使用Python函数时,只需 函数名(参数)
  3. ** # Ordering Spam, egg, Spam, Spam, bacon and Spam (4 more servings of Spam) **
    Python中注释符:#
  4. if spam_amount > 0:
    print(“But I don’t want ANY spam!”)

    强调行首缩进,并利用行首缩进划分代码块

2.作业总结

  1. 运算操作
    arithmetic operations
  2. 运算优先级
    括号>指数>乘除>加减

二、使用函数 定义函数

1. 使用help函数

help(round)
展示两条信息:
1. 函数头,包括参数
2. 函数功能的简短描述

2. 定义函数

基础格式:

	def 函数名 :
		函数体
		return 返回值

docstring
三重引号内部,可以有多行注释信息;
紧跟在函数名下,通常由简单的文字描述和函数示例组成
默认参数

	def greet(who="Colin"):
    	print("Hello,", who) 
	greet()
	greet(who="Kaggle")

将函数作为另一个函数的参数

	def mult_by_five(x):
    	return 5 * x

	def call(fn, arg):
    	"""Call fn on arg"""
    	return fn(arg)

	def squared_call(fn, arg):
    	"""Call fn on the result of calling fn on arg"""
    	return fn(fn(arg))

	print(
    	call(mult_by_five, 1),
    	squared_call(mult_by_five, 1), 
   	 sep='\n', # '\n' is the newline character - it starts a new line)

三、布尔和条件

1. 布尔

赋值
既可以直接赋值True/False,也可以用布尔操作式赋值
Comparison Operations
运算符优先级

  1. and > or
    example:
    True or True and False
    值为True
  2. 在复杂and、or、not运算中,推荐使用括号

2. 条件

if - elif - else
用:表示条件语句的结束,用行首缩进划分代码块

3. Boolean 转换

数值转换
int ( )、 float( )
布尔转换

  1. 除了0,其他所有的数都可被当作True
  2. 除了空白字符串,其他所有的字符串都可被当作True
  3. 通常空的序列(例如字符串、列表以及与字符串和列表相似的对象)都会被当作False

4. 习题内容

  1. 布尔运算符歧义 (未完全理解)
    have_umbrella or rain_level < 5 and have_hood or not rain_level > 0 and is_workday
    
    歧义原因:not rain_level > 0 and is_workday
    本意:not (rain_level > 0 and is_workday)
    实际:(not (rain_level > 0)) and is_workday
  2. 布尔转化为整数
    可以使用int()将布尔类型转化为整数类型,True为1,False为0
    但是,当对布尔类型数据进行运算操作时,Python会自动将其变为数据类型

四、列表

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']

1. 列表的定义

成员可以是数值、字符串、列表和混合元素

my_favourite_things = [32, 'raindrops on roses', help]

2. 下标

访问单个元素
列表名[下标]

3. 切片

列表名[切片起始下标:切片结束下标后一位]
例如:前三位元素的切片为:

planet[ 0 : 3 ]

并且起始下标和结束下标是可选择的,默认起始值为第一个,默认结束值为最后一个元素
切片示例

示例1:

# All the planets except the first and last
planets[1:-1]
['Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus']

示例2:

# The last 3 planets
planets[-3:]
['Saturn', 'Uranus', 'Neptune']

4. 修改列表

planets[3] = 'Malacandra'
planets[:3] = ['Mur', 'Vee', 'Ur']

5. 列表相关函数

  1. len()给出列表长度
  2. sorted()给出一个有序列表
  3. sum()求和
  4. max() min()最大 最小元素

6. 列表内置方法

  1. 列表名.append('元素')将元素添加至列表尾部
  2. 列表名.pop()删除列表中最后一个元素并将其返回
  3. 列表名.index('元素')返回元素在列表中的下标,当列表中不存在该元素时,会报错
  4. "元素" in 列表名当该元素在列表中时,返回True;反之返回False

五、元组

1.与列表仅有两处不同

  1. 元组的创建是用小括号 / 列表的创建是用方括号
  2. 元组内部元素不能被改变

2. 常用作函数返回多值

x = 0.125
x.as_integer_ratio()
(1, 8)

3. 元组中的多返回值可分别给变量赋值

numerator, denominator = x.as_integer_ratio()
print(numerator / denominator)
0.125

4. 交换两个变量

a = 1
b = 0
a, b = b, a
print(a, b)

习题相关

  1. 函数返回None:
    1. return
    2. return None
  2. 交换列表中元素
racers[0], racers[-1] = racers[-1], racers[0]
  1. 列表长度
d = [1, 2, 3][1:]
The expression is the same as the list [2, 3], which has length 2.
  1. 错题
    题目:We’re using lists to record people who attended our party and what order they arrived in. For example, the following list represents a party with 7 guests, in which Adela showed up first and Ford was the last to arrive:

party_attendees = [‘Adela’, ‘Fleda’, ‘Owen’, ‘May’, ‘Mona’, ‘Gilbert’, ‘Ford’]
A guest is considered ‘fashionably late’ if they arrived after at least half of the party’s guests. However, they must not be the very last guest (that’s taking it too far). In the above example, Mona and Gilbert are the only guests who were fashionably late.

Complete the function below which takes a list of party attendees as well as a person, and tells us whether that person is fashionably late.
题解:

def fashionably_late(arrivals, name):
    order = arrivals.index(name)
    return order >= len(arrivals) / 2 and order != len(arrivals) - 1

错解:

def fashionably_late(arrivals, name):
    """Given an ordered list of arrivals to the party and a name, return whether the guest with that
    name was fashionably late.
    """
    length = len(arrivals)
    if length % 2 == 0:
        start = (length / 2)
    else:
        start = ((length // 2) + 1)
    fashionably_late_name = arrivals[start : -1]
    return name in fashionably_late_name

报错信息:

TypeError: slice indices must be integers or None or have an __index__ method

订正:

def fashionably_late(arrivals, name):
    """Given an ordered list of arrivals to the party and a name, return whether the guest with that
    name was fashionably late.
    """
    length = len(arrivals)
    if length % 2 == 0:
        start = int(length / 2)
    else:
        start = int((length // 2) + 1)
    print(start)
    fashionably_late_name = arrivals[start : -1]
    return name in fashionably_late_name

六、 循环

1. 循环定义

1.1 for循环

planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
for planet in planets:
    print(planet, end=' ') # print all on same line

格式:for 变量名 in 集合名

  1. 规定了所使用的变量名称以及循环变量的集合
  2. 集合也可以是元组和字符串
  3. **range()**提供数字序列,有效用来循环遍历。例如:
for i in range(5):
    print("Doing important work. i =", i)

1.2 while循环

i = 0
while i < 10:
    print(i, end=' ')
    i += 1 # increase the value of i by 1

七、列表推导

1. 与for循环相关

示例1:

squares = [n**2 for n in range(10)]
squares
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

示例二

short_planets = [planet for planet in planets if len(planet) < 6]
short_planets
['Venus', 'Earth', 'Mars']

示例三:
左边的表达式不一定需要包含循环变量,虽然这种表达方式不实用

[32 for planet in planets]
[32, 32, 32, 32, 32, 32, 32, 32]

示例四:结合min,max,sun将极大程度减少代码行数
常规写法:

def count_negatives(nums):
    """Return the number of negative numbers in the given list.
    
    >>> count_negatives([5, -1, -2, 0, 3])
    2
    """
    n_negative = 0
    for num in nums:
        if num < 0:
            n_negative = n_negative + 1
    return n_negative

使用列表推导:

def count_negatives(nums):
    return len([num for num in nums if num < 0])

结合sum:

def count_negatives(nums):
    # Reminder: in the "booleans and conditionals" exercises, we learned about a quirk of 
    # Python where it calculates something like True + True + False + True to be equal to 3.
    return sum([num < 0 for num in nums])

2. 习题

1. 结合any函数的列表推导

def has_lucky_number(nums):
    return any([num % 7 == 0 for num in nums])

2. 错题

Implement a function that reproduces this behaviour, returning a list of booleans corresponding to whether the corresponding element is greater than n.

def elementwise_greater_than(L, thresh):
    res = []
    for ele in L:
        res.append(ele > thresh)
    return res
# the list comprehension version
def elementwise_greater_than(L, thresh): 
    return [ele > thresh for ele in L]

3. 错题

题目: Given a list of meals served over some period of time, return True if the same meal has ever been served two days in a row, and False otherwise.
错解1:

def menu_is_boring(meals):
	for meal in meals:
        index = meals.index(meal)
        if(meals[index+1] == meal):
            return True
    return False
# IndexError: list index out of range

错解2:

def menu_is_boring(meals):
	for i in len(meals):
        for j in (len(meals[i])-1):
            if(meals[j] == meals[(j+1)]):
                return True
    return False
# TypeError: 'int' object is not iterable

错解3:

def menu_is_boring(meals):
	for i in range(len(meals)):
        for j in range(len(meals[i])-1):
            if(meals[j] == meals[j+1]):
                return True
    return False
# Incorrect: When calling your function with arguments [['Egg', 'Spam']], Python raised the following exception... 
# IndexError: list index out of range
# 错误原因:被报错信息里的arguments [['Egg', 'Spam']]迷惑,以为是嵌套列表

答案:

def menu_is_boring(meals):
    # Iterate over all indices of the list, except the last one
    for i in range(len(meals)-1):
        if meals[i] == meals[i+1]:
            return True
    return False
# 总结:range(len(meals))将会给出meals中所有的下标

4. 好题

def estimate_average_slot_payout(n_runs):
	return ((sum([play_slot_machine() for i in range(n_runs)]) - n_runs) / n_runs)
print(estimate_average_slot_payout(10000000))
# 0.0256615

答案:

def estimate_average_slot_payout(n_runs):
    # Play slot machine n_runs times, calculate payout of each
    payouts = [play_slot_machine()-1 for i in range(n_runs)]
    # Calculate the average value
    avg_payout = sum(payouts) / n_runs
    return avg_payout
estimate_average_slot_payout(10000000)
# This should return an answer close to 0.025!

八、字符串

1. 相关语法

  1. 单引号和双引号等价,当内容中包含单引号时,建议外部使用双引号
    例如:
x = 'Pluto is a planet'
y = "Pluto is a planet"
x == y
#True
print("Pluto's a planet!")
print('My dog is named "Pluto"')
# Pluto's a planet!
# My dog is named "Pluto"
  1. 转义字符举例
    转移字符
  2. 三重引号可使字符串中包含真正的换行
    示例:
triplequoted_hello = """hello
world"""
print(triplequoted_hello)
triplequoted_hello == hello
# hello
# world
# True
  1. print()默认在当前输出完成后添加换行,除非我们对end元素赋值
    与输出函数相关的元素还有
    示例:
print("hello")
print("world")
print("hello", end='')
print("pluto", end='')

2. 字符串作为序列

相同操作:下标、切片、长度、作为循环变量集合
例如:

# Indexing
planet = 'Pluto'
planet[0]
# Slicing
planet[-3:]
# How long is this string?
len(planet)
# Yes, we can even loop over them
[char+'! ' for char in planet]

*不同操作:不能修改字符串,也不能使用append方法
例如:

planet[0] = 'B'
# planet.append doesn't work either

3. 字符串相关函数

  1. upper()将字符串内容全部转化为大写
  2. lower()将字符串内容全部转化为小写
  3. index('元素')在字符串中搜索所给元素是否在字符串中,并返回元素的第一个下标
  4. startswith(‘元素’) / endswith(‘元素’)判断字符串是否以所给元素开头/结尾
  5. split()将字符串划分为更小字符串的列表,默认划分值为空格;
words = claim.split()
words
# ['Pluto', 'is', 'a', 'planet!']

也可以设置划分值:

datestr = '1956-01-31'
year, month, day = datestr.split('-')
  1. join()将列表中的字符串连接为一整个字符串
'/'.join([month, day, year])
# '01/31/1956'
' 👏 '.join([word.upper() for word in words])
# 'PLUTO 👏 IS 👏 A 👏 PLANET!'
  1. format()重点: 串联字符串
    当不使用format函数串联字符串时:
planet + ", you'll always be the " + str(position) + "th planet to me."

其中,需要使用➕,且当插入元素为非字符串元素时,需要用str()将其转换为字符串元素
当使用format()函数串联字符串时:

"{}, you'll always be the {}th planet to me.".format(planet, position)

只需要将{}放在需要插入元素的位置即可,在后续的format()中写入需要插入到元素,其中,当需要插入的元素为非字符串元素时,format会自动将其转化并完成插入操作
format()其他作用:

pluto_mass = 1.303 * 10**22
earth_mass = 5.9722 * 10**24
population = 52910390
# 2 decimal points   3 decimal points, format as percent     separate with commas
"{} weighs about {:.2} kilograms ({:.3%} of Earth's mass). It is home to {:,} Plutonians.".format(planet, pluto_mass, pluto_mass / earth_mass, population)
# "Pluto weighs about 1.3e+22 kilograms (0.218% of Earth's mass). It is home to 52,910,390 Plutonians."

# Referring to format() arguments by index, starting from 0
s = """Pluto's a {0}.
No, it's a {1}.
{0}!
{1}!""".format('planet', 'dwarf planet')
print(s)

4. 习题

习题1:

题目: Given a string, it should return whether or not that string represents a valid zip code. For our purposes, a valid zip code is any string consisting of exactly 5 digits.
答案:

def is_valid_zip(zip_code):
    return len(zip_code) == 5 and zip_code.isdigit()

解析:
1.help(len):
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
2. help(str.isdigit)
Help on method_descriptor:
isdigit(self, /)
Return True if the string is a digit string, False otherwise.
A string is a digit string if all characters in the string are digits and there is at least one character in the string.

习题2:

题目:
A researcher has gathered thousands of news articles. But she wants to focus her attention on articles including a specific word. Complete the function below to help her filter her list of articles.
Your function should meet the following criteria:

  • Do not include documents where the keyword string shows up only as a part of a larger word. For example, if she were looking for the keyword “closed”, you would not include the string “enclosed.”
  • She does not want you to distinguish upper case from lower case letters. So the phrase “Closed the case.” would be included when the keyword is “closed”
  • Do not let periods or commas affect what is matched. “It is closed.” would be included when the keyword is “closed”. But you can assume there are no other types of punctuation.
    错解:
def word_search(doc_list, keyword):
	ret = []
    for i in range(len(doc_list)):
        doc = doc_list[i].lower()
        words = doc.split()
        if keyword in words:
            ret.append(i)
    return ret
# Incorrect: Expected return value of [1] given doc_list=['The Learn Python Challenge Casino', 'They bought a car, and a horse', 'Casinoville?'], keyword='car', but got [] instead.

答案:

def word_search(doc_list, keyword):
    # list to hold the indices of matching documents
    indices = [] 
    # Iterate through the indices (i) and elements (doc) of documents
    for i, doc in enumerate(doc_list):
        # Split the string doc into a list of words (according to whitespace)
        tokens = doc.split()
        # Make a transformed list where we 'normalize' each word to facilitate matching.
        # Periods and commas are removed from the end of each word, and it's set to all lowercase.
        normalized = [token.rstrip('.,').lower() for token in tokens]
        # Is there a match? If so, update the list of matching indices.
        if keyword.lower() in normalized:
            indices.append(i)
    return indices

解析:

  1. help(enumerate):
    Help on class enumerate in module builtins:
    class enumerate(object)
    | enumerate(iterable, start=0)
    |
    | Return an enumerate object.
    |
    | iterable
    | an object supporting iteration
    |
    | The enumerate object yields pairs containing a count (from start, which
    | defaults to zero) and a value yielded by the iterable argument.
    |
    | enumerate is useful for obtaining an indexed list:
    | (0, seq[0]), (1, seq[1]), (2, seq[2]), …
    |
    | Methods defined here:
    |
    | getattribute(self, name, /)
    | Return getattr(self, name).
    |
    | iter(self, /)
    | Implement iter(self).
    |
    | next(self, /)
    | Implement next(self).
    |
    | reduce(…)
    | Return state information for pickling.
    |
    | ----------------------------------------------------------------------
    | Static methods defined here:
    |
    | new(*args, **kwargs) from builtins.type
    | Create and return a new object. See help(type) for accurate signature.
  2. help(str.strip):
    Help on method_descriptor:
    strip(self, chars=None, /)
    Return a copy of the string with leading and trailing whitespace removed.
    If chars is given and not None, remove characters in chars instead.
  3. help(str.split):
    Help on method_descriptor:
    split(self, /, sep=None, maxsplit=-1)
    Return a list of the words in the string, using sep as the delimiter string.
    sep
    The delimiter according which to split the string.
    None (the default value) means split according to any whitespace,and discard empty strings from the result.
    maxsplit
    Maximum number of splits to do.
    -1 (the default value) means no limit.

九、字典

1. 键值对

numbers = {'one':1, 'two':2, 'three':3}

numbers['one']
# 1

numbers['eleven'] = 11
numbers
# {'one': 1, 'two': 2, 'three': 3, 'eleven': 11}

numbers['one'] = 'Pluto'
numbers
# {'one': 'Pluto', 'two': 2, 'three': 3, 'eleven': 11}

2. 字典推导

语法和列表推导一致

  1. 与for循环有关的推导
    结合字典循环和字符串作为列表对待
planets = ['Mercury', 'Venus', 'Earth', 'Mars', 'Jupiter', 'Saturn', 'Uranus', 'Neptune']
planet_to_initial = {planet: planet[0] for planet in planets}
planet_to_initial

其中,in可判断所给元素是否在字典中为键

'Saturn' in planet_to_initial
# True

for循环也是建立在字典的键之上

for k in numbers:
    print("{} = {}".format(k, numbers[k]))
# one = Pluto
# two = 2
# three = 3
# eleven = 11
  1. dict.keys() dict.values()获取字典中的所有键/值
# Get all the initials, sort them alphabetically, and put them in a space-separated string.
' '.join(sorted(planet_to_initial.values()))
# 'E J M M N S U V'
  1. dict.items()同时迭代键值对
for planet, initial in planet_to_initial.items():
    print("{} begins with \"{}\"".format(planet.rjust(10), initial))
#    Mercury begins with "M"
#      Venus begins with "V"
#      Earth begins with "E"
#       Mars begins with "M"
#    Jupiter begins with "J"
#     Saturn begins with "S"
#     Uranus begins with "U"
#    Neptune begins with "N"

3. 习题

与八.4.习题2相关
Now the researcher wants to supply multiple keywords to search for. Complete the function below to help her.
(You’re encouraged to use the word_search function you just wrote when implementing this function. Reusing code in this way makes your programs more robust and readable - and it saves typing!)

def multi_word_search(doc_list, keywords):
	"""
    信息:所给参数都是列表
    第一步:创建字典
        键:所给关键字;值:列表(关键字在列表中的下标组成)
    第二步:遍历关键字链表
        将关键字列表中的每一个元素都作为参数调用word_search function
        将word_search function的返回值作为 该关键值在字典中所对应的值
    """
    # 利用字典中的”字典推导“创建字典
    ret = {key:[] for key in keywords}
    for i in keywords:
        ret[i] = word_search(doc_list, i)
    return ret

十、imports

1. 举例:

import math
rint("It's math! It has type {}".format(type(math)))
# It's math! It has type <class 'module'>

print(dir(math)) # 查看该函数中的变量
"""
['__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']
"""

print("pi to 4 significant digits = {:.4}".format(math.pi))
# pi to 4 significant digits = 3.142

math.log(32, 2)
# 5.0

2. 其他调用语句:

import math as mt
mt.pi
# 3.141592653589793

3. import * 示例

from math import *
print(pi, log(32, 2))
# 3.141592653589793 5.0

4. import * 错误示例

from math import *
from numpy import *
print(pi, log(32, 2))
# TypeError: return arrays must be of ArrayType

错误原因: math和numpy都有log函数,后导入的numpy中的log函数会重写 math中的log函数
改正: 仅导入需要的部分

from math import log, pi
from numpy import asarray

5. 子模块 submodules

import numpy
print("numpy.random is a", type(numpy.random))
print("it contains names such as...",
      dir(numpy.random)[-15:]
     )
"""
numpy.random is a <class 'module'>
it contains names such as... ['seed', 'set_state', 'shuffle', 'standard_cauchy', 'standard_exponential', 'standard_gamma', 'standard_normal', 'standard_t', 'test', 'triangular', 'uniform', 'vonmises', 'wald', 'weibull', 'zipf']
"""
# Roll 10 dice
rolls = numpy.random.randint(low=1, high=6, size=10)
rolls
# array([4, 2, 4, 5, 3, 1, 4, 2, 5, 1])

6. work with strange types

1. type()

** what is this thing?**

type(rolls)
# numpy.ndarray

2. dir()

what can I do with it?

print(dir(rolls))
"""
['T', '__abs__', '__add__', '__and__', '__array__', '__array_finalize__', '__array_function__', '__array_interface__', '__array_prepare__', '__array_priority__', '__array_struct__', '__array_ufunc__', '__array_wrap__', '__bool__', '__class__', '__complex__', '__contains__', '__copy__', '__deepcopy__', '__delattr__', '__delitem__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__iand__', '__ifloordiv__', '__ilshift__', '__imatmul__', '__imod__', '__imul__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__ior__', '__ipow__', '__irshift__', '__isub__', '__iter__', '__itruediv__', '__ixor__', '__le__', '__len__', '__lshift__', '__lt__', '__matmul__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmatmul__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__setitem__', '__setstate__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__xor__', 'all', 'any', 'argmax', 'argmin', 'argpartition', 'argsort', 'astype', 'base', 'byteswap', 'choose', 'clip', 'compress', 'conj', 'conjugate', 'copy', 'ctypes', 'cumprod', 'cumsum', 'data', 'diagonal', 'dot', 'dtype', 'dump', 'dumps', 'fill', 'flags', 'flat', 'flatten', 'getfield', 'imag', 'item', 'itemset', 'itemsize', 'max', 'mean', 'min', 'nbytes', 'ndim', 'newbyteorder', 'nonzero', 'partition', 'prod', 'ptp', 'put', 'ravel', 'real', 'repeat', 'reshape', 'resize', 'round', 'searchsorted', 'setfield', 'setflags', 'shape', 'size', 'sort', 'squeeze', 'std', 'strides', 'sum', 'swapaxes', 'take', 'tobytes', 'tofile', 'tolist', 'tostring', 'trace', 'transpose', 'var', 'view']
"""
# If I want the average roll, the "mean" method looks promising...
rolls.mean()
# 3.1

# Or maybe I just want to turn the array into a list, in which case I can use "tolist"
rolls.tolist()
# [4, 2, 4, 5, 3, 1, 4, 2, 5, 1]

3. help()

tell me more

# That "ravel" attribute sounds interesting. I'm a big classical music fan.
help(rolls.ravel)
"""
Help on built-in function ravel:

ravel(...) method of numpy.ndarray instance
    a.ravel([order])
    
    Return a flattened array.
    
    Refer to `numpy.ravel` for full documentation.
    
    See Also
    --------
    numpy.ravel : equivalent function
    
    ndarray.flat : a flat iterator on the array.

"""

7. 运算符重载

[3, 4, 1, 2, 2, 1] + 10
# TypeError: can only concatenate list (not "int") to list

rolls + 10
# array([14, 12, 14, 15, 13, 11, 14, 12, 15, 11])
#  The designers of numpy arrays went a different way (adding the number to each element of the array).

与numpy有关的一些运算符:

# At which indices are the dice less than or equal to 3?
rolls <= 3
# array([False, True, False, False, True, True, False, True, False, True])
xlist = [[1,2,3],[2,4,6],]
# Create a 2-dimensional array
x = numpy.asarray(xlist)
print("xlist = {}\nx =\n{}".format(xlist, x))
"""
xlist = [[1, 2, 3], [2, 4, 6]]
x =
[[1 2 3]
 [2 4 6]]
"""
# Get the last element of the second row of our numpy array
x[1,-1]
# 6

# Get the last element of the second sublist of our nested list?
xlist[1,-1]
# TypeError: list indices must be integers or slices, not tuple

8. 1 + 1 != 2

tensorflow相关

9. 习题

1. 习题一

  1. Add the title “Results of 500 slot machine pulls”
  2. Make the y-axis start at 0.
  3. Add the label “Balance” to the y-axis
  4. format the numbers on the y-axis so they look like dollar amounts? e.g. $200 instead of just 200.
    答案:
def prettify_graph(graph):
    graph.set_title("Results of 500 slot machine pulls")
    # Make the y-axis begin at 0
    graph.set_ylim(bottom=0)
    # Label the y-axis
    graph.set_ylabel("Balance")
    # Bonus: format the numbers on the y-axis as dollar amounts
    # An array of the values displayed on the y-axis (150, 175, 200, etc.)
    ticks = graph.get_yticks()
    # Format those values into strings beginning with dollar sign
    new_labels = ['${}'.format(int(amt)) for amt in ticks]
    # Set the new labels
    graph.set_yticklabels(new_labels)

解析:

type(graph)
# matplotlib.axes._subplots.AxesSubplot

help(graph.set_title)
"""
Help on method set_title in module matplotlib.axes._axes:
set_title(label, fontdict=None, loc=None, pad=None, *, y=None, **kwargs) method of matplotlib.axes._subplots.AxesSubplot instance
    Set a title for the Axes.
    Set one of the three available Axes titles. The available titles
    are positioned above the Axes in the center, flush with the left
    edge, and flush with the right edge.
  
    Parameters
    ----------
    label : str
        Text to use for the title
    
    fontdict : dict
        A dictionary controlling the appearance of the title text,
        the default *fontdict* is::
    
           {'fontsize': rcParams['axes.titlesize'],
            'fontweight': rcParams['axes.titleweight'],
            'color': rcParams['axes.titlecolor'],
            'verticalalignment': 'baseline',
            'horizontalalignment': loc}
    
    loc : {'center', 'left', 'right'}, default: :rc:`axes.titlelocation`
        Which title to set.
    
    y : float, default: :rc:`axes.titley`
        Vertical Axes loation for the title (1.0 is the top).  If
        None (the default), y is determined automatically to avoid
        decorators on the Axes.
    
    pad : float, default: :rc:`axes.titlepad`
        The offset of the title from the top of the Axes, in points.
    
    Returns
    -------
    `.Text`
        The matplotlib text instance representing the title
    
    Other Parameters
    ----------------
    **kwargs : `.Text` properties
        Other keyword arguments are text properties, see `.Text` for a list
        of valid text properties.
"""

help(graph.set_ylim)
"""
Help on method set_ylim in module matplotlib.axes._base:

set_ylim(bottom=None, top=None, emit=True, auto=False, *, ymin=None, ymax=None) method of matplotlib.axes._subplots.AxesSubplot instance
    Set the y-axis view limits.
    
    Parameters
    ----------
    bottom : float, optional
        The bottom ylim in data coordinates. Passing *None* leaves the
        limit unchanged.
    
        The bottom and top ylims may also be passed as the tuple
        (*bottom*, *top*) as the first positional argument (or as
        the *bottom* keyword argument).
    
        .. ACCEPTS: (bottom: float, top: float)
    
    top : float, optional
        The top ylim in data coordinates. Passing *None* leaves the
        limit unchanged.
    
    emit : bool, default: True
        Whether to notify observers of limit change.
    
    auto : bool or None, default: False
        Whether to turn on autoscaling of the y-axis. *True* turns on,
        *False* turns off, *None* leaves unchanged.
    
    ymin, ymax : float, optional
        They are equivalent to bottom and top respectively,
        and it is an error to pass both *ymin* and *bottom* or
        *ymax* and *top*.
    
    Returns
    -------
    bottom, top : (float, float)
        The new y-axis limits in data coordinates.
    
    See Also
    --------
    get_ylim
    set_ybound, get_ybound
    invert_yaxis, yaxis_inverted
    
    Notes
    -----
    The *bottom* value may be greater than the *top* value, in which
    case the y-axis values will decrease from *bottom* to *top*.
    
    Examples
    --------
    >>> set_ylim(bottom, top)
    >>> set_ylim((bottom, top))
    >>> bottom, top = set_ylim(bottom, top)
    
    One limit may be left unchanged.
    
    >>> set_ylim(top=top_lim)
    
    Limits may be passed in reverse order to flip the direction of
    the y-axis. For example, suppose ``y`` represents depth of the
    ocean in m. The y-axis limits might be set like the following
    so 5000 m depth is at the bottom of the plot and the surface,
    0 m, is at the top.
    
    >>> set_ylim(5000, 0)
"""
help(graph.set_ylabel)
"""
Help on method set_ylabel in module matplotlib.axes._base:

set_ylabel(ylabel, fontdict=None, labelpad=None, *, loc=None, **kwargs) method of matplotlib.axes._subplots.AxesSubplot instance
    Set the label for the y-axis.
    
    Parameters
    ----------
    ylabel : str
        The label text.
    
    labelpad : float, default: :rc:`axes.labelpad`
        Spacing in points from the Axes bounding box including ticks
        and tick labels.  If None, the previous value is left as is.
    
    loc : {'bottom', 'center', 'top'}, default: :rc:`yaxis.labellocation`
        The label position. This is a high-level alternative for passing
        parameters *y* and *horizontalalignment*.
    
    Other Parameters
    ----------------
    **kwargs : `.Text` properties
        `.Text` properties control the appearance of the label.
    
    See Also
    --------
    text : Documents the properties supported by `.Text`.
"""
help(graph.set_xticklabels)
"""
Help on method set_xticklabels in module matplotlib.axes._base:

set_xticklabels(labels, *, fontdict=None, minor=False, **kwargs) method of matplotlib.axes._subplots.AxesSubplot instance
    Set the xaxis' labels with list of string labels.
    
    .. warning::
        This method should only be used after fixing the tick positions
        using `.Axes.set_xticks`. Otherwise, the labels may end up in
        unexpected positions.
    
    Parameters
    ----------
    labels : list of str
        The label texts.
    
    fontdict : dict, optional
        A dictionary controlling the appearance of the ticklabels.
        The default *fontdict* is::
    
           {'fontsize': rcParams['axes.titlesize'],
            'fontweight': rcParams['axes.titleweight'],
            'verticalalignment': 'baseline',
            'horizontalalignment': loc}
    
    minor : bool, default: False
        Whether to set the minor ticklabels rather than the major ones.
    
    Returns
    -------
    list of `.Text`
        The labels.
    
    Other Parameters
    ----------------
    **kwargs : `~.text.Text` properties.
"""
编程小白冲Kaggle每日打卡(6)--kaggle学堂:<Python>功能和获取帮助 本专栏旨在Kaggle官方课程的汉化,让大家更方便地看懂。 阅读详情

相关推荐

Nvidia GPU 入门教程之 08 如何在 Python 中使用 Kaggle API,直接从 Kaggle 快速下载数据集

Kaggle 是世界上所有数据科学的平台。就像一个奇怪的社交网络,到处都是数据科学家,到处都是 Jupyter 笔记本。这是一个学习和竞争的绝佳平台,这要归功于公司在网站上发布的数量惊人的比赛,这些公司正在寻找数据科学问题的解决方案,而无需花费太多。这个生态系统不出所料地产生了大量数据集——这就是你在这里的原因。你想用 Python 从 Kaggle 下载数据,这正是我们要做的。

iCloudEnd的博客 1620

用Python和Kaggle进行数据集标注的详细指南:探讨如何最好地使用和标注文本数据

作者:禅与计算机程序设计艺术 《65. 用Python和Kaggle进行数据集标注的详细指南:探讨如何最好地使用和标注文本数据》 使用 PyTorch 和 Kaggle 进行数据集

AI天才研究院 5328

Kaggle内核:Python快速运行Jupyter Notebook的技巧

Kaggle是全球数据科学竞赛的领导者,为数据科学家提供了一个展示才华、解决问题、学习新技能和扩展专业网络的平台。作为一个专业人士,理解Kaggle平台的运作原理和内核功能对于提升工作流程效率至关重要。Kaggle平台由Anthony Goldbloom在2010年创立,旨在推动数据分析和机器学习领域的进步。这里汇集了各个行业的数据集和挑战赛,数据科学家可以通过解决实际问题来测试和提升自己的技能。

weixin_33363025的博客 1294

使用jupyter快速下载kaggle中的数据集

通过jupyter快速下载kaggle数据集

SMBeterCD的博客 3080

内核运行:使用Kaggle内核立即运行任何Jupyter Notebook

kernel-run :fire: :rocket: 从任何Jupyter笔记本(本地文件或URL)立即创建并运行Kaggle内核。 $ pip install kernel-run --upgrade $ kernel-run path/to/notebook.ipynb Kernel created successfully: https://www.kaggle.com/aakashns/kr-notebook/edit $ kernel-run http://cs231n.stanford.edu/notebooks/pytorch_tutorial.ipynb Kernel created succ

Js逆向抖音a_bogus --/* V 1.0.1.19-fix.01 */补环境

需要在addEventListener中补一个鼠标移动事件,不补这个环境,生成的值是假值,你拿去请求,响应200,但是没有数据,这个算是dy的最难发现的一个难点。dy这个,没有原形链检测,我只是习惯了这样补,对XMLHttpRequest进行重写,导出a_bogus.发现可以响应状态码200,而且可以获取数据,接着注释params中的a_bogus。在n.apply的下面插入上述代码,对a_bogus进行全局导出。如果没有,就多放几次断点,因为每个人的游览器不一样。必须触发至少一次鼠标事件,不触发不给过。

2302_76420666的博客 4208

用于kaggle解决调用其它程序中自定义函数

解决kaggle中上传自己程序包调用自定义函数问题。

Ningmoua的博客 1592

解决PADs VX2.7安装中的License失效与软件卡死问题

本文详细解析了PADs VX2.7安装过程中常见的License失效与软件卡死问题,提供了从破解工具选择、环境变量设置到输入法兼容性调整等实用解决方案。特别推荐使用Siemens EDA系列新版破解工具,并分享性能调优与定期维护技巧,帮助工程师高效解决安装难题。

weixin_29234239的博客 826

Kaggle之Python

Kaggle之Python(函数、语法) 推荐一个特别特别好用的python学习平台——Kaggle(https://www.kaggle.com),墙裂推荐!!!(关于这个平台的注册和基本使用这里就不赘述,网上教程很多的) 我是从新手开始学的,虽然有Python代码经验,但是总感觉知识不够体系,所以来查缺补漏了,就当是一个随笔吧。 文章目录Kaggle之Python(函数、语法)help函数:显示函数语法和用例print函数:输出def:定义函数max函数:求最大值if...elif...else 条件语

扎尔其的博客 1059

VLM,VLA,VLN的区别与联系

VLM 提供了理解世界的“眼睛和大脑”,VLN 赋予了这个智能体在空间中“移动的双腿”,而 VLA 则进一步赋予了它“灵巧的双手”来改变世界。三者共同构成了一个完整具身智能体的核心能力模块。

l0409044222的博客 1321

Unity URP项目里Post Processing死活没效果?别慌,这5个坑我帮你踩过了

本文详细解析了Unity URP项目中Post Processing效果失效的五大常见问题,包括渲染管线配置冲突、Volume作用域误判、摄像机参数漏配、Layer层级冲突和Profile引用异常。通过实际项目案例和代码示例,提供专业级解决方案,帮助开发者快速排查并修复后处理效果不生效的问题。

weixin_33721427的博客 337

Kaggle入门课程之Python

第0讲 在kaggle中,是独立包含内核的,因此我们并不需要格外的编辑器来对我们所编写的语言进行编译.直接在kaggle内核这点击ctrl+回车运行即可. 内核的简单功能介绍 第一讲 语法 赋值运算 变量 数字 第二讲 ...

li123chen的博客 1224

【异常】Openclaw Gateway进程异常停止问题分析与解决方案

本文分析了Gateway服务异常停止的问题,提出了三种解决方案。核心问题是缺乏进程守护和自动恢复机制,导致服务崩溃后无法自行重启。推荐方案是使用PM2进程管理工具(方案1),提供进程监控、自动重启和开机自启功能。替代方案包括自定义守护脚本(方案2)和supervisord管理(方案3)。这些方案都能有效解决当前服务脆弱性问题,显著提升服务可用性,其中PM2方案成熟度高、配置简单,是首选解决方案。实施后可将服务从人工干预转变为自动恢复,确保业务连续性。

奶爸的编程之路,也就一周冷个三天 466

基于Python的Kaggle案例分析(一)

预测来自电子商务站点的搜索结果的准确性 案例大纲: 1、案例背景 2、数据预处理 3、特征工程 4、模型实现 1、案例背景        目前,小型在线企业没有很好的方法来评估其搜索算法的性能,使得他们难以提供卓越的客户体验。这个比赛的目的是创建一个可以用来衡量搜索结果相关性的开源模型,要求评估搜索算法准确性。        训练数据属性包括:         -----

yyxyyx10的博客 5446

【AUTOSAR-COM】-10.5-APP CAN Frame/PDU“发送周期不准“的影响因素

一个Tx PDU在COM模块中的数据流; Tx APP CAN Frame/PDU"发送周期不准"的影响因素;

「汽车电子助手」的博客 2390

20、自定义用户窗体:从创建到使用

本文详细介绍了在Excel VBA中创建和使用自定义用户窗体的完整过程,涵盖从窗体设计、控件添加与属性设置,到事件处理程序编写及宏调用的各个环节。通过实际示例讲解了如何实现文本大小写转换和员工信息录入等功能,并深入解析了常用控件的属性与事件机制。同时提供了控件命名规范、快捷键使用、布局技巧等实用建议,帮助读者构建高效、交互性强的VBA用户界面。

h0i1j2k3l的博客 134

Kaggle平台进行Python版本降级

kaggle平台进行python版本降级

Kagiri的博客 3366

上万条对话白分析了?智能客服质检避坑指南:90%团队倒在这些误区

当前客服质检普遍存在投入产出失衡的现象,根源在于十大误区:过度关注单点技术指标而忽视端到端解决能力、僵化的话术模板限制AI应变、数据孤岛阻碍知识进化、盲目追求拟人化牺牲效率、传统整改机制跟不上机器速度等。破局需重构质检体系,包括建立决策树质检法、设计复杂问题测试集、构建实时数据闭环、重置AI专属评价指标、实施分钟级热修复机制等。关键在于将质检从被动纠错升级为主动赋能,通过根因分析、场景化反馈、标准化评分和数据驱动优化,打造"问题诊断-改进-验证"

2202_75469062的博客 1544

python下载数据_用Python下载Kaggle数据

今天贡献一个小的技巧, 就是如何用Python下载Kaggle数据.为什么要用Python下载Kaggle数据呢? 对于一些数据量比较小的比赛, 当然可以直接打开浏览器, 然后在Kaggle的比赛主页上直接点击链接下载数据. 但是对于某些数据很大的比赛, 我希望能通过命令行或者Python直接下载数据. 另外, 有的时候我希望直接在服务器上通过命令行下载数据 (服务器上没有浏览器).如果你熟悉Li...

weixin_35197116的博客 1335

精雕软件(JDpaint) 5.5 绿色版

精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版精雕软件(JDpaint) 5.5 绿色版

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

Kaggle平台搭建指定Python版本CUDA版本Pytorch版本

在Kaggle平台上复现论文代码时,由于默认的Python版本较新,直接安装依赖库常会遇到兼容性问题。通过更改Python版本至3.8,可以有效解决这一问题。操作步骤包括在Kaggle Notebook界面添加Python版本,通过命令行更改并验证Python版本,确保选择GPU选项,并安装指定的CUDA和Pytorch版本。这一过程不仅解决了环境配置的难题,也为其他用户提供了实用的解决方案。感谢Kaggle社区成员提供的帮助,此分享旨在促进技术交流,如有侵权请联系删除。

Savitar_24的博客 2376

lwip-2.0.3

lwip是瑞典计算机科学院(SICS)的Adam Dunkels 开发的一个小型开源的TCP/IP协议栈。实现的重点是在保持TCP协议主要功能的基础上减少对RAM 的占用。

python+sklearn+kaggle机器学习

python+sklearn+kaggle机器学习0.kaggle1. 初级线性回归模型机器学习过程a. 提取数据b.数据预处理c.训练模型d.根据数据预测e.验证 今天是1024欸,发个贴拿个勋章 至于为什么1024这个数字很重要,因为1024是2的10次方 0.kaggle kaggle是一个学习ml也就是机器学习的平台 上面会有教程教如何用python写机器学习和各式各样的机器学习竞赛 1. 初级线性回归模型机器学习过程 a. 提取数据 通过pd(pandas)和sklearn下的split,从c

Eritque arcus的博客 1775

OV9734 DATASHEET,完整规格书

OV9734完整规格书,包括电气参数,尺寸规格,寄存器配置表等

Kaggle Python Docker 镜像使用教程

Kaggle Python Docker 镜像是Kaggle官方提供的一个Python运行环境,它允许用户在云端运行Python笔记本,参与Kaggle的竞赛和数据处理,而无需下载数据或配置环境。该镜像包含了运行Python笔记本所需的全部依赖和库。 ## 2. 项目快速启动 ### 本地构建镜像 首先,确保你的系统中已经安装了Docker。然后克隆项目仓库: ```shell git c...

gitblog_00314的博客 939

kaggle比赛_用 Python 写一个 Kaggle 比赛排行榜的爬虫

长久以来,我和小伙伴们都被 Kaggle 网站的加载速度困扰着,比如最近在用 Kaggle 上的数据集测试模型效果时,遇到排行榜(Leaderboard)刷新困难的问题。于是我们开始探索解决方案。首先尝试直接使用页面链接进行数据爬取,很明显爬不到,因为 Kaggle 的数据是异步响应的。于是我打开 Leaderboard 页面的开发者工具,以著名的 Titanic 竞赛的排行榜为例,打开 Netw...

weixin_39854369的博客 367

编程小白冲Kaggle每日打卡(5)--kaggle学堂:<Python>Hello,Python!

本专栏旨在Kaggle官方课程的汉化,让大家更方便地看懂。

killersll的博客 1291

Kaggle micro-courses 之 Python

Kaggle官方教程,用于data science必备的Python知识。 一、syntax,varibles and numbers 代码范例一: spam_amount = 0 print(spam_amount) # Ordering Spam, egg, Spam, Spam, bacon and Spam (4 more servings of Spam) spam_amount = ...

Cr的博客 423

Kaggle Python Docker 镜像安装与配置指南

Kaggle Python Docker 镜像是为Kaggle平台设计的Python运行环境。该镜像允许用户在云端运行Python笔记本,无需下载数据或配置环境。适用于参加Kaggle比赛或使用Kaggle数据集的开发者和数据科学家。 **主要编程语言**:Python ## 2. 关键技术和框架 该项目使用的关键技术包括: - Docker:用于容器化应用,提供一致的运行环境。 - Py...

gitblog_00603的博客 777
上一篇: 任何一个二目关系都是BCNF
下一篇: MiniConda使用
叁陆玖1024
博客等级 码龄8年 40粉丝 11原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址