numpy,pandas,matplotlib库例题

本文展示了使用numpy进行数组操作,包括创建数组、指定数据类型以及计算数组的和。同时,文章演示了pandas中Series的创建和操作,如布尔转换、数据合并。在可视化方面,通过matplotlib创建了多个子图,并尝试绘制图形时遇到了错误。最后,错误信息提示未识别的标记风格导致绘图失败。
摘要由CSDN通过智能技术生成
import numpy as np
a=np.array([1,2,3])
print(a)
[1 2 3]
import numpy as np
a = np.array([1,2,3],dtype=np.complex)
print(a)
[1.+0.j 2.+0.j 3.+0.j]


C:\Users\vers\AppData\Local\Temp\ipykernel_2852\1820813101.py:2: DeprecationWarning: `np.complex` is a deprecated alias for the builtin `complex`. To silence this warning, use `complex` by itself. Doing this will not modify any behavior and is safe. If you specifically wanted the numpy scalar type, use `np.complex128` here.
Deprecated in NumPy 1.20; for more details and guidance: https://numpy.org/devdocs/release/1.20.0-notes.html#deprecations
  a = np.array([1,2,3],dtype=np.complex)
import numpy as np
x=np.float32(5)
print('x为;',x)
print('x为对象的data属性:',x.data)
print('x为对象的size属性:',x.size)
print('x为对象的维数:',x.ndim)
y=np.bool_(x)
print('转换为bool类型的x为:',y)
z=np.float16(y)
print('True值转换为float16类型为:',z)

x为; 5.0
x为对象的data属性: <memory at 0x00000297718EBA40>
x为对象的size属性: 1
x为对象的维数: 0
转换为bool类型的x为: True
True值转换为float16类型为: 1.0
import numpy as np
arr=np.array([[0,1,2],[3,4,5]])
print(arr)
print(arr.sum(axis=0))
print(arr.sum(axis=1))
[[0 1 2]
 [3 4 5]]
[3 5 7]
[ 3 12]
import numpy as np
stus_score = np.array([[45,65],[56,78],[34,67],[35,78],[51,76]])
result=[stus_score>50]
print(result)
[array([[False,  True],
       [ True,  True],
       [False,  True],
       [False,  True],
       [ True,  True]])]
import pandas as pd
s=pd.Series([1,3,5,9,6,8])
print(s)
0    1
1    3
2    5
3    9
4    6
5    8
dtype: int64
import pandas as pd
print('--------列表创建series---------')
s1=pd.Series([1,1,1,1,1])
print(s1)
print('--------字典创建series---------')
s2=pd.Series({'Longitude':39,'Latitude':116,'Temperature':23})
print('First value in s2:',s2['Longitude'])
print('--------用序列作series索引-----')
s3=pd.Series([3.4,0.8,2.1,0.3,1.5],range(5,10))
print('First value in s3:',s3[5])
--------列表创建series---------
0    1
1    1
2    1
3    1
4    1
dtype: int64
--------字典创建series---------
First value in s2: 39
--------用序列作series索引-----
First value in s3: 3.4
s2["city"]="beijing"
s2['Temperature']+=2
s2
Longitude           39
Latitude           116
Temperature         25
city           beijing
dtype: object
s3[s3>2]
5    3.4
7    2.1
dtype: float64
stiny = pd.Series({'humidity':84})
s4=s2.append(stiny)
print('------------原Series:-------------\n',s2)
print('------------新Series:-------------\n',s4)
------------原Series:-------------
 Longitude           39
Latitude           116
Temperature         25
city           beijing
dtype: object
------------新Series:-------------
 Longitude           39
Latitude           116
Temperature         25
city           beijing
humidity            84
dtype: object


C:\Users\vers\AppData\Local\Temp\ipykernel_2852\741578432.py:2: FutureWarning: The series.append method is deprecated and will be removed from pandas in a future version. Use pandas.concat instead.
  s4=s2.append(stiny)
import matplotlib.pyplot as plt
fig=plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,4)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-3Gf8kGuN-1677944301144)(output_10_0.png)]

fig=plt.figure()
ax1=fig.add_subplot(2,2,1)
ax2=fig.add_subplot(2,2,2)
ax3=fig.add_subplot(2,2,3)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-IQhwI3cE-1677944301145)(output_11_0.png)]

fig,axes=plt.subplots(2,3)
axes
array([[<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>],
       [<AxesSubplot:>, <AxesSubplot:>, <AxesSubplot:>]], dtype=object)

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-jHRrqwTT-1677944301146)(output_12_1.png)]

import numpy as np
import matplotlib.pyplot as plt
xp=np.linspace(-10,10,100)
yp=np.sin(xp)
plt.plot(xp,yp,marker="0")
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

D:\python\lib\site-packages\matplotlib\markers.py in _set_marker(self, marker)
    325             try:
--> 326                 Path(marker)
    327                 self._marker_function = self._set_vertices


D:\python\lib\site-packages\matplotlib\path.py in __init__(self, vertices, codes, _interpolation_steps, closed, readonly)
    129         vertices = _to_unmasked_float_array(vertices)
--> 130         _api.check_shape((None, 2), vertices=vertices)
    131 


D:\python\lib\site-packages\matplotlib\_api\__init__.py in check_shape(_shape, **kwargs)
    163 
--> 164             raise ValueError(
    165                 f"{k!r} must be {len(target_shape)}D "


ValueError: 'vertices' must be 2D with shape (M, 2). Your input has shape ().


The above exception was the direct cause of the following exception:


ValueError                                Traceback (most recent call last)

~\AppData\Local\Temp\ipykernel_2852\2286491374.py in <module>
      3 xp=np.linspace(-10,10,100)
      4 yp=np.sin(xp)
----> 5 plt.plot(xp,yp,marker="0")


D:\python\lib\site-packages\matplotlib\pyplot.py in plot(scalex, scaley, data, *args, **kwargs)
   2767 @_copy_docstring_and_deprecators(Axes.plot)
   2768 def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
-> 2769     return gca().plot(
   2770         *args, scalex=scalex, scaley=scaley,
   2771         **({"data": data} if data is not None else {}), **kwargs)


D:\python\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
   1630         """
   1631         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1632         lines = [*self._get_lines(*args, data=data, **kwargs)]
   1633         for line in lines:
   1634             self.add_line(line)


D:\python\lib\site-packages\matplotlib\axes\_base.py in __call__(self, data, *args, **kwargs)
    310                 this += args[0],
    311                 args = args[1:]
--> 312             yield from self._plot_args(this, kwargs)
    313 
    314     def get_next_color(self):


D:\python\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs, return_kwargs)
    536             return list(result)
    537         else:
--> 538             return [l[0] for l in result]
    539 
    540 


D:\python\lib\site-packages\matplotlib\axes\_base.py in <listcomp>(.0)
    536             return list(result)
    537         else:
--> 538             return [l[0] for l in result]
    539 
    540 


D:\python\lib\site-packages\matplotlib\axes\_base.py in <genexpr>(.0)
    529             labels = [label] * n_datasets
    530 
--> 531         result = (make_artist(x[:, j % ncx], y[:, j % ncy], kw,
    532                               {**kwargs, 'label': label})
    533                   for j, label in enumerate(labels))


D:\python\lib\site-packages\matplotlib\axes\_base.py in _makeline(self, x, y, kw, kwargs)
    349         default_dict = self._getdefaults(set(), kw)
    350         self._setdefaults(default_dict, kw)
--> 351         seg = mlines.Line2D(x, y, **kw)
    352         return seg, kw
    353 


D:\python\lib\site-packages\matplotlib\lines.py in __init__(self, xdata, ydata, linewidth, linestyle, color, marker, markersize, markeredgewidth, markeredgecolor, markerfacecolor, markerfacecoloralt, fillstyle, antialiased, dash_capstyle, solid_capstyle, dash_joinstyle, solid_joinstyle, pickradius, drawstyle, markevery, **kwargs)
    369         self._color = None
    370         self.set_color(color)
--> 371         self._marker = MarkerStyle(marker, fillstyle)
    372 
    373         self._markevery = None


D:\python\lib\site-packages\matplotlib\markers.py in __init__(self, marker, fillstyle)
    233         self._marker_function = None
    234         self._set_fillstyle(fillstyle)
--> 235         self._set_marker(marker)
    236 
    237     def _recache(self):


D:\python\lib\site-packages\matplotlib\markers.py in _set_marker(self, marker)
    327                 self._marker_function = self._set_vertices
    328             except ValueError as err:
--> 329                 raise ValueError('Unrecognized marker style {!r}'
    330                                  .format(marker)) from err
    331 


ValueError: Unrecognized marker style '0'

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-Y66NxRIJ-1677944301147)(output_13_1.png)]

import matplotlib.pyplot as plt
import numpy as np
a=np.arange(10)
plt.xlabel('x')
plt.ylabel('y')
plt.plot(a,a*1.5,a,a*2.5,a,a*3.5,a,a*4.5)
plt.legend(['1.5x','2.5x','3.5x','4.5x'])
plt.title('simple lines')
plt.show()

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MUubrU8z-1677944301147)(output_14_0.png)]

import numpy as np
import matplotlib.pyplot as plt
fig,axes=plt.subplots(2,1)
plt.subplot(2,1,1)
x=np.linspace(-10,10,100)
y=np.sin(x)
plt.plot(x,y,marker="0")
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

D:\python\lib\site-packages\matplotlib\markers.py in _set_marker(self, marker)
    325             try:
--> 326                 Path(marker)
    327                 self._marker_function = self._set_vertices


D:\python\lib\site-packages\matplotlib\path.py in __init__(self, vertices, codes, _interpolation_steps, closed, readonly)
    129         vertices = _to_unmasked_float_array(vertices)
--> 130         _api.check_shape((None, 2), vertices=vertices)
    131 


D:\python\lib\site-packages\matplotlib\_api\__init__.py in check_shape(_shape, **kwargs)
    163 
--> 164             raise ValueError(
    165                 f"{k!r} must be {len(target_shape)}D "


ValueError: 'vertices' must be 2D with shape (M, 2). Your input has shape ().


The above exception was the direct cause of the following exception:


ValueError                                Traceback (most recent call last)

~\AppData\Local\Temp\ipykernel_2852\2820513652.py in <module>
      5 x=np.linspace(-10,10,100)
      6 y=np.sin(x)
----> 7 plt.plot(x,y,marker="0")


D:\python\lib\site-packages\matplotlib\pyplot.py in plot(scalex, scaley, data, *args, **kwargs)
   2767 @_copy_docstring_and_deprecators(Axes.plot)
   2768 def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
-> 2769     return gca().plot(
   2770         *args, scalex=scalex, scaley=scaley,
   2771         **({"data": data} if data is not None else {}), **kwargs)


D:\python\lib\site-packages\matplotlib\axes\_axes.py in plot(self, scalex, scaley, data, *args, **kwargs)
   1630         """
   1631         kwargs = cbook.normalize_kwargs(kwargs, mlines.Line2D)
-> 1632         lines = [*self._get_lines(*args, data=data, **kwargs)]
   1633         for line in lines:
   1634             self.add_line(line)


D:\python\lib\site-packages\matplotlib\axes\_base.py in __call__(self, data, *args, **kwargs)
    310                 this += args[0],
    311                 args = args[1:]
--> 312             yield from self._plot_args(this, kwargs)
    313 
    314     def get_next_color(self):


D:\python\lib\site-packages\matplotlib\axes\_base.py in _plot_args(self, tup, kwargs, return_kwargs)
    536             return list(result)
    537         else:
--> 538             return [l[0] for l in result]
    539 
    540 


D:\python\lib\site-packages\matplotlib\axes\_base.py in <listcomp>(.0)
    536             return list(result)
    537         else:
--> 538             return [l[0] for l in result]
    539 
    540 


D:\python\lib\site-packages\matplotlib\axes\_base.py in <genexpr>(.0)
    529             labels = [label] * n_datasets
    530 
--> 531         result = (make_artist(x[:, j % ncx], y[:, j % ncy], kw,
    532                               {**kwargs, 'label': label})
    533                   for j, label in enumerate(labels))


D:\python\lib\site-packages\matplotlib\axes\_base.py in _makeline(self, x, y, kw, kwargs)
    349         default_dict = self._getdefaults(set(), kw)
    350         self._setdefaults(default_dict, kw)
--> 351         seg = mlines.Line2D(x, y, **kw)
    352         return seg, kw
    353 


D:\python\lib\site-packages\matplotlib\lines.py in __init__(self, xdata, ydata, linewidth, linestyle, color, marker, markersize, markeredgewidth, markeredgecolor, markerfacecolor, markerfacecoloralt, fillstyle, antialiased, dash_capstyle, solid_capstyle, dash_joinstyle, solid_joinstyle, pickradius, drawstyle, markevery, **kwargs)
    369         self._color = None
    370         self.set_color(color)
--> 371         self._marker = MarkerStyle(marker, fillstyle)
    372 
    373         self._markevery = None


D:\python\lib\site-packages\matplotlib\markers.py in __init__(self, marker, fillstyle)
    233         self._marker_function = None
    234         self._set_fillstyle(fillstyle)
--> 235         self._set_marker(marker)
    236 
    237     def _recache(self):


D:\python\lib\site-packages\matplotlib\markers.py in _set_marker(self, marker)
    327                 self._marker_function = self._set_vertices
    328             except ValueError as err:
--> 329                 raise ValueError('Unrecognized marker style {!r}'
    330                                  .format(marker)) from err
    331 


ValueError: Unrecognized marker style '0'

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MdmjhOHR-1677944301148)(output_15_1.png)]


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值