学习python有关统计基础部分课程总结

本文是对学习Python统计基础课程的总结,涵盖了函数、标量、列表、字典、字符串格式化、读取CSV文件、日期和时间、对象、map和lambda函数、numpy以及Pandas的Series和DataFrame等内容。强调了Python数据类型的操作、文件读取、时间处理、正则表达式、数据操作和数据结构转换等核心知识点。

花了整整两天的时间学习一门关于python用来做统计的基础课程。现在总结一下。基本的原则是列出一些代码的实例,表明学到的pythong包括numpy和pandas的基本功能。如果可以用一个函数表示的就用一个函数,不用多个函数,这样容易跟踪。不过刚刚学完,思想上很觉得疲劳。这个总结可能要慢慢做起来。做完了再分享出去。

函数

def add_numbers(x, y, z=None, flag=False):
    if flag:
        print('flag is true')
    if z == None:
        return x + y
    else:
        return x + y + z

print(add_numbers(1, 2, flag=True))

要点:

1) python的函数参数是可以有默认值的

2) 调用带有默认参数值的函数时,可以指定哪个参数的默认值被改写

def add_numbers(x, y):
    return x + y
f = add_numbers
f(1, 2)

要点:

1)函数可以赋值给变量

标量,列表,字典

x = (1, 'a', 2, 'b')
type(x)
#tuple

x = [1, 'a', 2, 'b']
x.append(3.3)

[1]*3
# [1, 1, 1]

[1,2] + [3,4]
# [1, 2, 3, 4]

print(x[1])
print(x[1:2])
print(x[-3, -1])

x = {'a':'b', 'c':'d'}
print(x['a'])

for e in x:
    print(x[e])

for v in x.values():
    print(v)

for e,v in x.items():
    print(e)
    print(v)

要点:

1)python的标量,列表,字典可以保存不同类型的值

2)列表的一些基本操作,像append(), *, +

3)字典的遍历key,value,和item的方法

字符串格式打印

sales_statement = '{} bought {} item(s) at a price of {} each for a total of {}'
print(sales_statement.format('Chris', 4, 3.24, 4 * 3.24))

要点:

1) 怎么像java或者c++那样在字符串里打印变量值

读取CSV文件

import csv 

%precision 2

with open('mpg.csv') as csvfile:
    mpg = list(csv.DictReader(csvfile))

mpg[0].keys()
# dict_keys(['mpg', 'cylinders', 'displacement', 'horsepower', 'weight', 'acceleration', 'model_year', 'origin', 'name'])

sum(float(d['acceleration']) for d in mpg)

# 6196.10

要点:

1)如何将CSV文件的每一行按照字典的方式读出来

2)怎样访问读出来的字典的内容

日期和时间

import datetime as dt
import time as tm

tm.time()
# 1605049825.93

dtnow = dt.datetime.fromtimestamp(tm.time())
dtnow
# datetime.datetime(2020, 11, 10, 15, 11, 18, 593011)

dtnow.year, dtnow.month
# (2020, 11)

today = dt.date.today()
today
# datetime.date(2020, 11, 10)

要点:

1)怎么使用时间戳和日期

2)怎么在时间戳和日期之间转换

对象

class Person:
    department = 'school of information'
    
    def set_name(self, new_name):
        self.name = new_name

要点:

1)怎么定义类和类里面的属性和方法

map函数

store1 = [10.00, 11.00, 12.34, 2.34]
store2 = [9.00, 11.10, 12.34, 2.01]
cheapest = map(min, store1, store2) # lazy execution

list(cheapest)
# [9.00, 11.00, 12.34, 2.01]

要点:

1)map函数是lazy execution的

lambda函数

my_function = lambda a, b, c : a + b
my_function(1, 2, 3)
# 3

people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']

def split_title_and_name(person):
    return person.split()[0] + ' ' + person.split()[-1]

#option 1
for person in people:
    print(split_title_and_name(person) == (lambda person:person.split()[0] + ' ' + person.split()[-1])(person))

要点:

1)lambda函数的写法

numpy

import numpy as np
import math

#array creation
a = np.array([1, 2, 3])
print(a) # [1, 2, 3]
print(a.ndim) # 1

b = np.array([[1, 2, 3], [4, 5, 6]])
b
# array([[1, 2, 3],
#       [4, 5, 6]])

b.shape
# (2,3)

b.dtype
#dtype('int32')

d = np.zeros((2, 3))
print(d)
# [[0. 0. 0.]
# [0. 0. 0.]]

np.random.rand(2,3)
# array([[0.74956529, 0.33373396, 0.19966149],
#       [0.35464706, 0.24963549, 0.31511589]])

f = np.arange(10, 50, 2)
f
# array([10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42,
#       44, 46, 48])

np.linspace(0, 2, 15)
# array([0.        , 0.14285714, 0.28571429, 0.42857143, 0.57142857,
#        0.71428571, 0.85714286, 1.        , 1.14285714, 1.28571429,
#        1.42857143, 1.57142857, 1.71428571, 1.85714286, 2.        ])

要点:

1)怎么从list创建numpy array

2)怎样显示numpy array维度的数量,维度,数据类型

3)怎样用numpy创建全零array,随机array, 步进式array,和平均分布array

a = np.array([10, 20, 30, 40])
b = np.array([1, 2, 3, 4])
d = a * b
print(d)
# [ 10  40  90 160]

# booilean array
d > 50
# array([False, False,  True,  True])

A = np.array([[1, 1], [0, 1]])
B = np.array([[2, 0], [3, 4]])
print(A*B)
# [[2 0]
#  [0 4]]

print(A.sum())
print(A.max())
print(A.min())
print(A.mean())
# 3
# 1
# 0
# 0.75

要点:

1)array的乘法

2)array的布尔型array

3)array的sum,max, min, 和mean

b = np.arange(1, 16, 1).reshape(3, 5)
print(b)

# [[ 1  2  3  4  5]
#  [ 6  7  8  9 10]
#  [11 12 13 14 15]]

from PIL import Image
from IPython.display import display
im = Image.open('momo.JPG')
display(im)

array=np.array(im)
mask = np.full(array.shape,255)

modified_array=array-mask
modified_array=modified_array*-1
modified_array=modified_array.astype(np.uint8)

display(Image.fromarray(modified_array))

modified_array.shape
reshaped=np.reshape(modified_array,[3648, 2736, 3])
print(reshaped.shape)
display(Image.fromarray(reshaped))

要点:

1)怎样改变一个array的维度

a = np.array([1, 2,3])
a[2] # 3

a = np.array([[1,2], [3,4], [5,6]])
a[1,1] # 4

wines = np.genfromtxt('winequality-red.csv', delimiter=';', skip_header=1)
print(wines[:,0])
print(wines[:, 0:1])

wines[:,-1].mean()

要点:

1)怎么访问numpy数组里的元素

2)怎么从csv文件读取成numpy数组

正则表达式

import re
text = 'this is a good day'
if re.search('good', text):
    print('wonderful')
else:
    print('alas: :(')

要点:

1)re.search()

text = 'amy works diligently. amy gets good grades. our study amy is successful.'
re.findall('amy', text) # ['amy', 'amy', 'amy']

grades='ACAAABCBCBAA'
re.findall('[A][B-C]', grades) # ['AC', 'AB']
re.findall('AB|AC', grades) # ['AC', 'AB']
re.findall('[^A]', grades) # ['C', 'B', 'C', 'B', 'C', 'B']
re.findall('A{2,10}', grades) # ['AAA', 'AA']

要点:

1)re.findall()

2)正则表达式的一些语法

Pandas Series

import pandas as pd
studentds = ['alice', 'jack', 'molly']
pd.Series(studentds)

# 0    alice
# 1     jack
# 2    molly
# dtype: object

要点:

1)怎么从array生成Series

np.nan == None
np.isnan(np.nan) # True

要点:

1)怎么判断None

studentds_scores = {'alice': 'physices', 'jack': 'chemistry'}
s = pd.Series(studentds_scores)
s
# alice     physices
# jack     chemistry
# dtype: object

s.index
# Index(['alice', 'jack'], dtype='object')

s = pd.Series(['phsices', 'chemistry'], index=['alice', 'jack'])
s
# alice      phsices
# jack     chemistry
# dtype: object

students_scores = {'alice': 'physices', 'jack': 'chemistry'}
s = pd.Series(students_scores, index=['alice', 'sam'])
s
# alice    physices
# sam           NaN
# dtype: object

要点:

1)怎么从dictionary转变成Series

2)怎么指定Series Index

studentds_scores = {'alice': 'physices', 'jack': 'chemistry'}
s = pd.Series(studentds_scores)

s.iloc[1]
# 'chemistry'

s.loc['jack']
# 'chemistry'

s[1] # not recommended
# 'chemistry'

s['jack'] # not recommended
# 'chemistry'

要点:

1)怎么通过位置索引访问Series值

2)怎么通过Index的值访问Series值

grades = pd.Series([90, 80, 70,  60])
total =np.sum(grades)
print(total / len(grades))
# 75.0

numbers = pd.Series(np.random.randint(0, 1000, 10000))
numbers.head()

numbers+=2

for label,value in numbers.iteritems():
    numbers.at[label] = value+2
numbers.head()

要点:

1)Series上的操作是整体操作,像numpy.sum(),’+‘等

2)遍历Series方法

s = pd.Series([1, 2, 3])
s.loc['history'] = 102
s
# 0            1
# 1            2
# 2            3
# history    102
# dtype: int64

要点:

1)通过[]给Series增加一行key/value

students_classes = pd.Series({'alice': 'physics',
                             'jack': 'chemistry'})

kelly_classes = pd.Series(['phi', 'art', 'math'], index=['kelly', 'kelly', 'kelly'])

all_students_classes = students_classes.append(kelly_classes)
all_students_classes

# alice      physics
# jack     chemistry
# kelly          phi
# kelly          art
# kelly         math
# dtype: object

all_students_classes.loc['kelly']

# kelly     phi
# kelly     art
# kelly    math
# dtype: object

要点:

1)怎么连接两个Series

2)Series的key是可以重复的

DataFrame

record1 = pd.Series({'name': 'alice', 'class': 'physics'})
record2 = pd.Series({'name': 'jack', 'class': 'chemistry'})
record3 = pd.Series({'name': 'molly', 'class': 'biology'})
df = pd.DataFrame([record1, record2, record3], index=['school1', 'school2', 'school3'])
df.head()

#           name	class
# school1	alice	physics
# school2	jack	chemistry
# school3	molly	biology

students = [{'name': 'alice', 'class': 'physics'}, {'name': 'jack', 'class': 'chemistry'}, {'name': 'molly', 'class': 'biology'}]
df = pd.DataFrame(students, index=['school1', 'school2', 'school1'])
df.head()

#           name	class
# school1	alice	physics
# school2	jack	chemistry
# school3	molly	biology

要点:

1)怎么从一个Series数组转变成DataFrame

2)怎么从一个Dictionary数组转变成DataFrame

df.loc['school2']
# name          jack
# class    chemistry
# Name: school2, dtype: object

type(df.loc['school2'])
# pandas.core.series.Series

df.loc['school1']
#           name	class
# school1	alice	physics
# school1	molly	biology

type(df.loc['school1'])
# pandas.core.frame.DataFrame

df.loc['school1', 'name']
# school1    alice
# school1    molly
# Name: name, dtype: object

要点:

1)根据返回的数据DataFrame可能会返回Series或者DataFrame

df.T
#     	school1	school2	school1
# name	alice	jack	molly
# class	physics	chemistry	biology

要点:

1)怎么转置一个DataFrame

df.loc[:,['name']] # colon means that we want to get all of the rows

要点:

1)怎么取得某一个index的所有行

df.drop('school1')

要点:

1)怎么删掉某一个DataFrame的key

copy_df = df.copy()
copy_df.drop('name', inplace=True, axis=1)

要点:

1)怎么删掉DataFrame的列

2)怎么直接删掉正在操作的DataFrame的数据

df['rank'] = None
df
#         	name	class	rank
# school1	alice	physics	None
# school2	jack	chemistry	None
# school1	molly	biology	None

要点:

1)怎么增加DataFrame的列

df = pd.read_csv('Admission_Predict.csv')
df.head()

要点:

1)怎么从csv读取成DataFrame

df = pd.read_csv('Admission_Predict.csv', index_col=0)
df.head()

要点:

1)怎么指定某一列作为Index

new_df = df.rename(columns={'GRE Score':'GRE Score', 'TOEFL Score':'TOEFL Score', 'University Rating':'University Rating', 
                            'SOP':'Statement of Purpose', 'LOR': 'Letter of Recommendation', 'Chance of Admit': 'Chance of Admit'})
new_df.head()

要点:

1)怎么重新命名列名

new_df.columns

new_df = new_df.rename(mapper=str.strip, axis='columns')
new_df.head()

要点:

1)怎么运用map修改列名

2)怎么显示列名

cols = list(df.columns)
cols = [x.lower().strip() for x in cols]
df.columns = cols

要点:

1)怎么使用list修改一个DF的列名

admit_mask = df['chance of admit'] > 0.7
df.where(admit_mask).head()
df.where(admit_mask).dropna().head()

要点:

1)怎样根据某一列的值生成一个boolean mask

2)怎样使用boolean mask选择一个DF中符合要求的行

3)怎么去除DF中带有na的行

df[df['chance of admit'] > 0.7].head()

要点:

1)这是对于df.where(admit_mask).dropna()的一种简写方式

df['chance of admit'].gt(0.7) & df['chance of admit'].lt(0.9)

要点:

1)多个条件生成boolean mask的书写方式,注意和(df['chance of admit']>0.7) & (df['chance of admit']<0.9)是不同的

df['Serial Number'] = df.index
df.columns = [x.strip() for x in df.columns]
df = df.set_index('Chance of Admit')
df = df.reset_index()

要点:

1)怎么将index的值赋给一列

2)怎么将一列设置成index

3)怎么重新使用默认index

df['SUMLEV'].unique()
df=df[df['SUMLEV']==50]

要点:

1)怎么得到一列中不重复的值

2)怎么得到某一列值为指定值的所有行

columns_to_keep = ['STNAME', 'CTYNAME']
df = df[columns_to_keep]

要点:

1)怎么只保留一个DF中的部分列

df = df.set_index(['STNAME', 'CTYNAME'])
df.loc['Michigan', 'Washtenaw County']
df.loc[[('Michigan', 'Washtenaw County')]]

要点:

1)对于一个DF可以指定两个column作为index

2)有两个column做index时怎么访问某一个index的行

mask = df.isnull()

df.dropna()

df.fillna(0, inplace=True)

要点:

1)怎么生成为null值的mask

2)怎么去除有na的数据

3)怎么将na转换成一个默认值

df = df.set_index('time')
df = df.sort_index()

要点:

1)怎么给index排序

df = df.fillna(method='ffill')

要点:

1)使用ffill做向前填充

df.replace(1, 100)

df.replace([1, 3], [100, 300])

df.replace(to_replace=".*html$", value='webpage', regex=True)

df['First'] = df['First'].replace('[ ].*', '', regex=True)

要点:

1)怎么替换一个值

2)怎么替换多个值

3) 怎么使用regex对字符串的值进行替换

4)怎么对某一列的值进行替换

del(df['First'])

要点:

1)怎么删除掉一列

def splitname(row):
    row['First'] = row['President'].split(' ')[0]
    row['Last'] = row['President'].split(' ')[-1]
    return row

df = df.apply(splitname, axis='columns')

要点:

1)怎么利用一个函数给一个df增加列

pattern = '(^[\w]*)(?:.*)([\w]*$)'
df['President'].str.extract(pattern).head()

要点:

1)从一个df的列利用extract生成一个新的df

pd.merge(staff_df, student_df, how='outer', left_index=True, right_index=True)

pd.merge(staff_df, student_df, how='inner', left_index=True, right_index=True)

pd.merge(staff_df, student_df, how='right', on='name')

pd.merge(staff_df, student_df, how='inner', on=['first name', 'last name'])

要点:

1)怎么做outer和inner merge

2)怎么指定一列进行merge

3)怎么指定多列进行merge

frames=[df_2011, df_2012, df_2013]
pd.concat(frames)

pd.concat(frames, keys=['2011', '2012', '2013'])

要点:

1)怎么纵向合并frame

2)怎么在纵向合并时指定key值

# Pandas idiom - chain
(df.where(df['SUMLEV']==50)).dropna().set_index(['STNAME', 'CTYNAME']).rename(columns={'ESTIMATESBASE2010':'Estimates Base 2010'})

要点:

1)pandas的链式书写方法

import timeit

def first_approach():
    global df
    return (df.where(df['SUMLEV']==50)).dropna()

timeit.timeit(first_approach, number=10)

要点:

1)使用timeit对一个函数的性能进行测量

def min_max(row):
    data = row[['POPESTIMATE2010','POPESTIMATE2011','POPESTIMATE2012','POPESTIMATE2013','POPESTIMATE2014','POPESTIMATE2015']]
    return pd.Series({'min': np.min(data), 'max': np.max(data)})

df.apply(min_max, axis='columns').head()


def min_max(row):
    data = row[['POPESTIMATE2010','POPESTIMATE2011','POPESTIMATE2012','POPESTIMATE2013','POPESTIMATE2014','POPESTIMATE2015']]
    row['max'] = np.max(data)
    row['min'] = np.min(data)
    return row
df.apply(min_max, axis='columns')

rows = ['POPESTIMATE2010','POPESTIMATE2011','POPESTIMATE2012','POPESTIMATE2013','POPESTIMATE2014','POPESTIMATE2015']
df.apply(lambda x: np.max(x[rows]), axis=1).head()

要点:

1)怎样使用apply生成一个DF里若干列的最大和最小值的Series

2)怎样使用apply在一个DF里怎样增加若干列的最大值和最小值的列

3) 怎么使用lambda求得DF里若干列的最大值

def get_state_region(x):
    northeast = ['Connecticut', 'Maine']
    midwest = ['Illiois', 'Indiana']
    south = ['Delaware', 'Florida']
    west = ['Arizona', 'Colorado']
    if x in northeast:
        return 'Northeast'
    elif x in midwest:
        return 'Midwest'
    elif x in south:
        return "Sourth"
    elif x in west:
        return "West"
    else:
        return 'Unknown'

df['state_region'] = df['STNAME'].apply(lambda x: get_state_region(x))

要点:

1)怎样使用apply和lambda从DF的某一个列值生成一个新列的值

%%timeit -n 3
for state in df['STNAME'].unique():
    avg = np.average(df.where(df['STNAME']==state).dropna()['CENSUS2010POP'])
    print('Counties in state ' + state + ' have an average population of ' + str(avg))

%%timeit -n 3
for group, frame in df.groupby('STNAME'):
    avg = np.average(frame['CENSUS2010POP'])
    print('Counties in state ' + group + ' have an average ppulation of ' + str(avg))

要点:

1)在Jupyter notebook里使用"%%timeit -n"计算执行的时间

2)使用where计算以一列的值分组得到统计数据的方法(average)

3)使用DataFrame.groupby计算以一列的值分组得到统计数据的方法(average)

df = df.set_index('STNAME') # must set as index at first

def set_batch_number(item):
    if item[0]<'M':
        return 0
    if item[0] < 'Q':
        return 1
    return 2

for group, frame in df.groupby(set_batch_number):
    print('there are ' + str(len(frame)) + ' recors in group ' + str(group) + ' for processing')

要点:

1)怎样使用一个函数对某一个列的值进行处理过之后再分组

df.columns = [x.strip() for x in df.columns]
df = df.set_index(['cancellation_policy', 'review_scores_value'])

for group, frame in df.groupby(level=(0,1)):
    print(group)

要点:

1)怎样对于有多个index的df进行分组

def grouping_fun(item):
    if item[1] == 10.0:
        return (item[0], "10.0")
    else:
        return (item[0], "not 10.0")
    
for group, frame in df.groupby(by=grouping_fun):
    print(group)

要点:

1)怎样使用函数对df的index进行改变然后进行分组

df.groupby('cancellation_policy').agg({'review_scores_value':(np.nanmean, np.nanstd), "reviews_per_month":np.nanmean})

要点:

1)怎样使用groupby和agg对一个df就某一个列进行分组然后对某些列计算集合统计数据

cols = ['cancellation_policy', 'review_scores_value']
transform_df = df[cols].groupby('cancellation_policy').transform(np.nanmean)
transform_df.head()

要点:

1)对于groupby之后transform的使用

def calc_mean_review_scores(group):
    avg = np.nanmean(group['review_scores_value'])
    group['review_scores_mean'] = np.abs(avg - group['review_scores_value'])
    return group

df.groupby('cancellation_policy').apply(calc_mean_review_scores).head()

要点:

1)怎样使用apply在groupby之后对group进行处理

pd.cut(df, 10)

要点:

1)使用cut把数据分成若干桶

def create_category(ranking):
    if (ranking>=1) & (ranking<100):
        return 'tier1'
    elif (ranking < 200):
        return 'tier2'
    elif (ranking < 300):
        return 'tier3'
    else:
        return 'other tier'

df['rank_level'] = df['world_rank'].apply(lambda x: create_category(x))
df.head()

df.pivot_table(values='score', index='country', columns='rank_level', aggfunc=[np.mean]).head()

要点:

1)怎样使用pivot_table来将某一列里的值转换成列,并执行aggregation操作

df.pivot_table(values='score', index='country', columns='rank_level', aggfunc=[np.mean, np.max], margins=True).head()

要点:

1)pivot_table里margins的使用,在set成True时会生成一列计算所有列的aggregation操作

new_df = new_df.stack()

new_df.unstack().head()

要点:

1)DataFrame对stack和unstack的使用。有些复杂,基本的意识是stack将column变成index,unstack将index变成column

pd.Timestamp('9/1/2019 10:05am') # Timestamp('2019-09-01 10:05:00')

pd.Timestamp('9/1/2019 10:05am').isoweekday() # 7

pd.Period('1/2016')

pd.Period('1/2016') + 5 # Period('2016-06', 'M')

d1 = ['2 June 2013', 'Aug 29 2014', '2015-06-26', '7/12/16']
ts3 = pd.DataFrame(np.random.randint(10, 100, (4, 2)), index=d1, columns=list('ab'))

ts3.index = pd.to_datetime(ts3.index)

pd.to_datetime('4.7.12', dayfirst=True) # Timestamp('2012-07-04 00:00:00')

pd.Timestamp('9/3/2016') - pd.Timestamp('9/1/2016') # Timedelta('2 days 00:00:00')

pd.Timestamp('9/4/2016') + pd.offsets.Week() # Timestamp('2016-09-11 00:00:00')

dates = pd.date_range('10-01-2016', periods=9, freq='2W-SUN')
dates

# DatetimeIndex(['2016-10-02', '2016-10-16', '2016-10-30', '2016-11-13',
#               '2016-11-27', '2016-12-11', '2016-12-25', '2017-01-08',
#               '2017-01-22'],
#              dtype='datetime64[ns]', freq='2W-SUN')

要点:

1)pandas的Timestamp, Period, date_rangte的使用

2)pandas使用to_datetime来将string转换成TimeStamp

from scipy.stats import ttest_ind

ttest_ind(early_finishers['assignment1_grade'], late_finishers['assignment1_grade'])

要点:

1)对ttest_ind的使用,计算两组独立的数列的相似性。还没有仔细学习具体用法和背后理论。

import networkx as nx

edgelist = [['Mannheim', 'Frankfurt', 85], ['Mannheim', 'Karlsruhe', 80], ['Erfurt', 'Wurzburg', 186], ['Munchen', 'Numberg', 167], ['Munchen', 'Augsburg', 84], ['Munchen', 'Kassel', 502], ['Numberg', 'Stuttgart', 183], ['Numberg', 'Wurzburg', 103], ['Numberg', 'Munchen', 167], ['Stuttgart', 'Numberg', 183], ['Augsburg', 'Munchen', 84], ['Augsburg', 'Karlsruhe', 250], ['Kassel', 'Munchen', 502], ['Kassel', 'Frankfurt', 173], ['Frankfurt', 'Mannheim', 85], ['Frankfurt', 'Wurzburg', 217], ['Frankfurt', 'Kassel', 173], ['Wurzburg', 'Numberg', 103], ['Wurzburg', 'Erfurt', 186], ['Wurzburg', 'Frankfurt', 217], ['Karlsruhe', 'Mannheim', 80], ['Karlsruhe', 'Augsburg', 250],["Mumbai", "Delhi",400],["Delhi", "Kolkata",500],["Kolkata", "Bangalore",600],["TX", "NY",1200],["ALB", "NY",800]]

g = nx.Graph()

for edge in edgelist:
    g.add_edge(edge[0], edge[1], weight=edge[2])

nx.draw_networkx(nx.minimum_spanning_tree(g))

要点:

1)network的使用。可以处理和图有关的数据。

总结:总体上觉得收获挺多的。不过还是要在实践中继续学习和巩固,才能完全掌握。继续加油!

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值