100% found this document useful (1 vote)
66 views

Import As

The document shows examples of using various NumPy functions and methods to manipulate arrays, generate random numbers, plot graphs, and more. Key functions and methods demonstrated include arange(), reshape(), linspace(), sin(), plot(), rand(), and others. NumPy is used to efficiently work with multi-dimensional arrays and matrices for tasks like data analysis, engineering, and science applications.

Uploaded by

Fozia Dawood
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
66 views

Import As

The document shows examples of using various NumPy functions and methods to manipulate arrays, generate random numbers, plot graphs, and more. Key functions and methods demonstrated include arange(), reshape(), linspace(), sin(), plot(), rand(), and others. NumPy is used to efficiently work with multi-dimensional arrays and matrices for tasks like data analysis, engineering, and science applications.

Uploaded by

Fozia Dawood
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

In 

[5]: import numpy as np


In [6]: a=np.arange(6)
a

Out[6]: array([0, 1, 2, 3, 4, 5])

In [7]: a.reshape(2,3)

Out[7]: array([[0, 1, 2],

[3, 4, 5]])

In [8]: a.any()

Out[8]: True

In [9]: a.all()

Out[9]: False

In [10]: a.mean()

Out[10]: 2.5

In [11]: a.argmin()

Out[11]: 0

In [12]: a.argmin()

Out[12]: 0

In [13]: a.cumsum()

Out[13]: array([ 0, 1, 3, 6, 10, 15])

In [14]: a.sum()

Out[14]: 15

In [15]: a.cumprod()

Out[15]: array([0, 0, 0, 0, 0, 0])

In [ ]: ​

In [ ]: ​
In [16]: np.linspace(-5,5,100)

Out[16]: array([-5. , -4.8989899 , -4.7979798 , -4.6969697 , -4.5959596 ,

-4.49494949, -4.39393939, -4.29292929, -4.19191919, -4.09090909,

-3.98989899, -3.88888889, -3.78787879, -3.68686869, -3.58585859,

-3.48484848, -3.38383838, -3.28282828, -3.18181818, -3.08080808,

-2.97979798, -2.87878788, -2.77777778, -2.67676768, -2.57575758,

-2.47474747, -2.37373737, -2.27272727, -2.17171717, -2.07070707,

-1.96969697, -1.86868687, -1.76767677, -1.66666667, -1.56565657,

-1.46464646, -1.36363636, -1.26262626, -1.16161616, -1.06060606,

-0.95959596, -0.85858586, -0.75757576, -0.65656566, -0.55555556,

-0.45454545, -0.35353535, -0.25252525, -0.15151515, -0.05050505,

0.05050505, 0.15151515, 0.25252525, 0.35353535, 0.45454545,

0.55555556, 0.65656566, 0.75757576, 0.85858586, 0.95959596,

1.06060606, 1.16161616, 1.26262626, 1.36363636, 1.46464646,

1.56565657, 1.66666667, 1.76767677, 1.86868687, 1.96969697,

2.07070707, 2.17171717, 2.27272727, 2.37373737, 2.47474747,

2.57575758, 2.67676768, 2.77777778, 2.87878788, 2.97979798,

3.08080808, 3.18181818, 3.28282828, 3.38383838, 3.48484848,

3.58585859, 3.68686869, 3.78787879, 3.88888889, 3.98989899,

4.09090909, 4.19191919, 4.29292929, 4.39393939, 4.49494949,

4.5959596 , 4.6969697 , 4.7979798 , 4.8989899 , 5. ])

vedio

panda series
In [17]: np.zeros(((2,2,2)))

Out[17]: array([[[0., 0.],

[0., 0.]],

[[0., 0.],

[0., 0.]]])

In [18]: np.zeros(2)

Out[18]: array([0., 0.])

In [19]: np.ones((2,3))

Out[19]: array([[1., 1., 1.],

[1., 1., 1.]])

In [20]: np.empty((1,2))

Out[20]: array([[0., 0.]])


In [21]: np.eye(3)

Out[21]: array([[1., 0., 0.],

[0., 1., 0.],

[0., 0., 1.]])

In [22]: np.diag([1,2,3,4])

Out[22]: array([[1, 0, 0, 0],

[0, 2, 0, 0],

[0, 0, 3, 0],

[0, 0, 0, 4]])

In [23]: b=np.arange(15)
b

Out[23]: array([ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])

In [24]: c=b.reshape(3,5)
c

Out[24]: array([[ 0, 1, 2, 3, 4],

[ 5, 6, 7, 8, 9],

[10, 11, 12, 13, 14]])

In [25]: c[0:2,:]

Out[25]: array([[0, 1, 2, 3, 4],

[5, 6, 7, 8, 9]])

In [26]: c[2,1:3]

Out[26]: array([11, 12])

In [27]: c[0:3,1::2]

Out[27]: array([[ 1, 3],

[ 6, 8],

[11, 13]])

In [28]: x=np.arange(9)
x

Out[28]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])

In [29]: y=x.reshape(3,3)
y

Out[29]: array([[0, 1, 2],

[3, 4, 5],

[6, 7, 8]])
In [30]: z=y+y
z

Out[30]: array([[ 0, 2, 4],

[ 6, 8, 10],

[12, 14, 16]])

In [31]: z.sum()

Out[31]: 72

In [32]: z.sum(axis=0)

Out[32]: array([18, 24, 30])

In [33]: z.sum(axis=1)

Out[33]: array([ 6, 24, 42])

In [34]: print(np.char.strip(['anita','babaad'],'a'))

['nit' 'babaad']

In [35]: a=np.arange(9)
a

Out[35]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])

In [36]: np.split(a,3)

Out[36]: [array([0, 1, 2]), array([3, 4, 5]), array([6, 7, 8])]

In [37]: np.split(a,[3,5,7])

Out[37]: [array([0, 1, 2]), array([3, 4]), array([5, 6]), array([7, 8])]

In [38]: a =np.arange(1,7)
a

Out[38]: array([1, 2, 3, 4, 5, 6])

In [39]: a.reshape(3,2)

Out[39]: array([[1, 2],

[3, 4],

[5, 6]])

In [40]: np.resize(a,(2,3))

Out[40]: array([[1, 2, 3],

[4, 5, 6]])
In [41]: import matplotlib.pyplot as plt

In [42]: a = np.array([20,15,12,87,4,40,53,74,56,51,40,15 ,79,25,27])


plt.hist(a,bins=[0,20,40,60,80,100])
plt.title('hisogram')

plt.show()
In [43]: a = np.array([0,20,40,60,70,80,100])
plt.hist(a,bins=10)
plt.title('hisogram')

plt.show()
In [44]: a= np.arange(5)
a
b= np.log10(a)
b

C:\Users\HP\AppData\Local\Temp\ipykernel_9568\3214265231.py:3: RuntimeWarning:
divide by zero encountered in log10

b= np.log10(a)

Out[44]: array([ -inf, 0. , 0.30103 , 0.47712125, 0.60205999])

In [45]: x= np.arange(0,3*np.pi,0.1)
y=np.sin(x)
plt.plot(x,y)

Out[45]: [<matplotlib.lines.Line2D at 0x16216fe1450>]

In [46]: x=np.linspace(-5,5,10)
x

Out[46]: array([-5. , -3.88888889, -2.77777778, -1.66666667, -0.55555556,

0.55555556, 1.66666667, 2.77777778, 3.88888889, 5. ])


In [47]: x= np.arange(0,3*np.pi,0.1)
x

Out[47]: array([0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1. , 1.1, 1.2,

1.3, 1.4, 1.5, 1.6, 1.7, 1.8, 1.9, 2. , 2.1, 2.2, 2.3, 2.4, 2.5,

2.6, 2.7, 2.8, 2.9, 3. , 3.1, 3.2, 3.3, 3.4, 3.5, 3.6, 3.7, 3.8,

3.9, 4. , 4.1, 4.2, 4.3, 4.4, 4.5, 4.6, 4.7, 4.8, 4.9, 5. , 5.1,

5.2, 5.3, 5.4, 5.5, 5.6, 5.7, 5.8, 5.9, 6. , 6.1, 6.2, 6.3, 6.4,

6.5, 6.6, 6.7, 6.8, 6.9, 7. , 7.1, 7.2, 7.3, 7.4, 7.5, 7.6, 7.7,

7.8, 7.9, 8. , 8.1, 8.2, 8.3, 8.4, 8.5, 8.6, 8.7, 8.8, 8.9, 9. ,

9.1, 9.2, 9.3, 9.4])

In [48]: x= np.linspace(0,3*np.pi,90)
y=np.sin(x)
plt.plot(x,y)

Out[48]: [<matplotlib.lines.Line2D at 0x1621703f520>]


In [49]: z= np.random.rand(10,10)
z

Out[49]: array([[0.23625247, 0.78075186, 0.2649629 , 0.23755606, 0.21993028,

0.36851016, 0.49456666, 0.76930498, 0.75750532, 0.64742577],

[0.37402652, 0.68186037, 0.12463372, 0.72974855, 0.08223705,

0.15251225, 0.74402859, 0.26020794, 0.10611529, 0.02563067],

[0.90908211, 0.21832064, 0.01765496, 0.24955885, 0.20045802,

0.78860053, 0.77450483, 0.94944447, 0.43006646, 0.05496481],

[0.55767738, 0.91775442, 0.91414497, 0.28652073, 0.92100904,

0.73458746, 0.64143294, 0.99154067, 0.55808655, 0.80090747],

[0.47387659, 0.04504894, 0.44199545, 0.58168346, 0.44957267,

0.93481276, 0.53725608, 0.48046475, 0.49686263, 0.1266272 ],

[0.80558675, 0.28861892, 0.66093707, 0.38026209, 0.095633 ,

0.01594691, 0.20634501, 0.50199497, 0.28724525, 0.29711762],

[0.27825947, 0.58637245, 0.96422689, 0.49354773, 0.47023825,

0.82977358, 0.49589789, 0.50423491, 0.87693999, 0.97868539],

[0.02566709, 0.89329526, 0.37831596, 0.44272094, 0.09137165,

0.03219234, 0.38268379, 0.86497383, 0.62770482, 0.65486253],

[0.16869952, 0.22422863, 0.60100765, 0.86540663, 0.75261578,

0.87677397, 0.53458297, 0.89260201, 0.5923787 , 0.70274573],

[0.56206124, 0.86240696, 0.63056697, 0.60315971, 0.11824551,

0.37859756, 0.84009612, 0.39154193, 0.12804247, 0.07920471]])

In [50]: z[np.random.randint(5,size=2), np.random.randint(5,size=2)]=np.nan


z

Out[50]: array([[0.23625247, 0.78075186, 0.2649629 , nan, 0.21993028,

0.36851016, 0.49456666, 0.76930498, 0.75750532, 0.64742577],

[0.37402652, 0.68186037, 0.12463372, 0.72974855, 0.08223705,

0.15251225, 0.74402859, 0.26020794, 0.10611529, 0.02563067],

[0.90908211, 0.21832064, 0.01765496, 0.24955885, 0.20045802,

0.78860053, 0.77450483, 0.94944447, 0.43006646, 0.05496481],

[0.55767738, 0.91775442, 0.91414497, 0.28652073, 0.92100904,

0.73458746, 0.64143294, 0.99154067, 0.55808655, 0.80090747],

[0.47387659, 0.04504894, 0.44199545, nan, 0.44957267,

0.93481276, 0.53725608, 0.48046475, 0.49686263, 0.1266272 ],

[0.80558675, 0.28861892, 0.66093707, 0.38026209, 0.095633 ,

0.01594691, 0.20634501, 0.50199497, 0.28724525, 0.29711762],

[0.27825947, 0.58637245, 0.96422689, 0.49354773, 0.47023825,

0.82977358, 0.49589789, 0.50423491, 0.87693999, 0.97868539],

[0.02566709, 0.89329526, 0.37831596, 0.44272094, 0.09137165,

0.03219234, 0.38268379, 0.86497383, 0.62770482, 0.65486253],

[0.16869952, 0.22422863, 0.60100765, 0.86540663, 0.75261578,

0.87677397, 0.53458297, 0.89260201, 0.5923787 , 0.70274573],

[0.56206124, 0.86240696, 0.63056697, 0.60315971, 0.11824551,

0.37859756, 0.84009612, 0.39154193, 0.12804247, 0.07920471]])


In [51]: a=np.arange(6)
print(a)
b=a.reshape(2,3)
print("\n")
print(b)
print("\n")
print(b.sum(axis=0))
print("\n")
print(b.sum(axis=1))
print("\n")
print(b.sum())

[0 1 2 3 4 5]

[[0 1 2]

[3 4 5]]

[3 5 7]

[ 3 12]

15

In [52]: print(np.sqrt(a))
print(np.std(a))

[0. 1. 1.41421356 1.73205081 2. 2.23606798]

1.707825127659933

In [53]: print(a.ravel())

[0 1 2 3 4 5]

In [54]: a=np.zeros((6,6),dtype=complex)
a

Out[54]: array([[0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],

[0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],

[0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],

[0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],

[0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j],

[0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j, 0.+0.j]])


In [56]: a=np.zeros((6,6),dtype=int)
print(a)
a[::2,1::2]=1
a

[[0 0 0 0 0 0]

[0 0 0 0 0 0]

[0 0 0 0 0 0]

[0 0 0 0 0 0]

[0 0 0 0 0 0]

[0 0 0 0 0 0]]

Out[56]: array([[0, 1, 0, 1, 0, 1],

[0, 0, 0, 0, 0, 0],

[0, 1, 0, 1, 0, 1],

[0, 0, 0, 0, 0, 0],

[0, 1, 0, 1, 0, 1],

[0, 0, 0, 0, 0, 0]])

Type Markdown and LaTeX: 𝛼2


Pandas
In [57]: import pandas as pd
arr = [1,2,3,4,5]
s = pd.Series(arr)
s

Out[57]: 0 1

1 2

2 3

3 4

4 5

dtype: int64

In [58]: arr = [1,2,3,4]


ind = ['a','b','c','d','e']
s = pd.Series(arr)
s

Out[58]: 0 1

1 2

2 3

3 4

dtype: int64
In [59]: a = np.random.randn(5)
a
index = ['a','b','c','d','e']
b=pd.Series(a,index=index)
b

Out[59]: a -0.089431

b 0.654129

c 1.414282

d 0.307507

e 0.500292

dtype: float64

In [60]: d={'a':1,'b':2,'c':3}
d

Out[60]: {'a': 1, 'b': 2, 'c': 3}

In [61]: a = pd.Series(d)
a

Out[61]: a 1

b 2

c 3

dtype: int64

In [62]: a.index = ['A','B','C']


a

Out[62]: A 1

B 2

C 3

dtype: int64

In [63]: a[1:3]

Out[63]: B 2

C 3

dtype: int64

In [64]: a[:2]

Out[64]: A 1

B 2

dtype: int64
In [65]: x=s.append(a)
x

C:\Users\HP\AppData\Local\Temp\ipykernel_9568\1146264426.py:1: FutureWarning: T
he series.append method is deprecated and will be removed from pandas in a futu
re version. Use pandas.concat instead.

x=s.append(a)

Out[65]: 0 1

1 2

2 3

3 4

A 1

B 2

C 3

dtype: int64
In [66]: x.drop('b')

---------------------------------------------------------------------------

KeyError Traceback (most recent call last)

Cell In [66], line 1

----> 1 x.drop('b')

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\util\_d
ecorators.py:331, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.
wrapper(*args, **kwargs)

325 if len(args) > num_allow_args:

326 warnings.warn(

327 msg.format(arguments=_format_argument_list(allow_args)),

328 FutureWarning,

329 stacklevel=find_stack_level(),

330 )

--> 331 return func(*args, **kwargs)

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\se
ries.py:5237, in Series.drop(self, labels, axis, index, columns, level, inplac
e, errors)

5140 @deprecate_nonkeyword_arguments(version=None, allowed_args=["self", "la


bels"])

5141 def drop( # type: ignore[override]

5142 self,

(...)

5149 errors: IgnoreRaise = "raise",

5150 ) -> Series | None:

5151 """

5152 Return Series with specified index labels removed.

5153

(...)

5235 dtype: float64

5236 """

-> 5237 return super().drop(

5238 labels=labels,

5239 axis=axis,

5240 index=index,

5241 columns=columns,

5242 level=level,

5243 inplace=inplace,

5244 errors=errors,

5245 )

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\util\_d
ecorators.py:331, in deprecate_nonkeyword_arguments.<locals>.decorate.<locals>.
wrapper(*args, **kwargs)

325 if len(args) > num_allow_args:

326 warnings.warn(

327 msg.format(arguments=_format_argument_list(allow_args)),

328 FutureWarning,

329 stacklevel=find_stack_level(),

330 )

--> 331 return func(*args, **kwargs)

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\ge
neric.py:4505, in NDFrame.drop(self, labels, axis, index, columns, level, inpla
ce, errors)

4503 for axis, labels in axes.items():

4504 if labels is not None:

-> 4505 obj = obj._drop_axis(labels, axis, level=level, errors=errors)

4507 if inplace:

4508 self._update_inplace(obj)

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\ge
neric.py:4546, in NDFrame._drop_axis(self, labels, axis, level, errors, only_sl
ice)

4544 new_axis = axis.drop(labels, level=level, errors=errors)

4545 else:

-> 4546 new_axis = axis.drop(labels, errors=errors)

4547 indexer = axis.get_indexer(new_axis)

4549 # Case for non-unique axis

4550 else:

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\in
dexes\base.py:6975, in Index.drop(self, labels, errors)

6973 if mask.any():

6974 if errors != "ignore":

-> 6975 raise KeyError(f"{list(labels[mask])} not found in axis")

6976 indexer = indexer[~mask]

6977 return self.delete(indexer)

KeyError: "['b'] not found in axis"

In [ ]: arr1= [1,2,3,4]


arr2 = [2,5,6,7]
a1=pd.Series(arr1)
b1=pd.Series(arr2)
print(a1)
print(b1)

In [ ]: a1.add(b1)

In [ ]: a.sub(b)

In [ ]: a.mul(b)

In [ ]: a.div(b)

In [ ]: print(a.median())
print(a.max())
print(a.min())
In [67]: dates = pd.date_range('today',periods = 6)
dates

Out[67]: DatetimeIndex(['2022-12-07 17:34:58.765917', '2022-12-08 17:34:58.765917',

'2022-12-09 17:34:58.765917', '2022-12-10 17:34:58.765917',

'2022-12-11 17:34:58.765917', '2022-12-12 17:34:58.765917'],

dtype='datetime64[ns]', freq='D')

In [68]: num= np.random.randn(6,4)


num
col = ['A','B','C','D']
df = pd.DataFrame(num, index = dates, columns=col)
df

Out[68]:
A B C D

2022-12-07 17:34:58.765917 -0.061036 0.877063 1.196815 1.021173

2022-12-08 17:34:58.765917 1.603865 -1.192769 1.781787 -0.908768

2022-12-09 17:34:58.765917 -0.928322 -0.909172 -1.745287 0.095972

2022-12-10 17:34:58.765917 0.677686 -0.271046 1.663527 0.018025

2022-12-11 17:34:58.765917 -0.263337 -1.091150 -0.853208 -0.439662

2022-12-12 17:34:58.765917 0.855528 -0.739296 0.072859 0.014840

In [69]: n=np.arange(5)
n

Out[69]: array([0, 1, 2, 3, 4])

In [70]: m=pd.DataFrame(n)
m

Out[70]:
0

0 0

1 1

2 2

3 3

4 4
In [71]: data = {'animals':['cat','dog','cat','dog','snake'],
'age':[2,2.5,np.nan,4.5,3],
'visits':[1,2,3,2,1]}
labels= ['a','b','c','d','e']
df = pd.DataFrame(data, index = labels)
df

Out[71]:
animals age visits

a cat 2.0 1

b dog 2.5 2

c cat NaN 3

d dog 4.5 2

e snake 3.0 1

In [72]: df.dtypes

Out[72]: animals object

age float64

visits int64

dtype: object

In [73]: df.head()

Out[73]:
animals age visits

a cat 2.0 1

b dog 2.5 2

c cat NaN 3

d dog 4.5 2

e snake 3.0 1

In [74]: df.tail(4)

Out[74]:
animals age visits

b dog 2.5 2

c cat NaN 3

d dog 4.5 2

e snake 3.0 1
In [75]: df['animals']

Out[75]: a cat

b dog

c cat

d dog

e snake

Name: animals, dtype: object

In [ ]: ​

In [ ]: ​

In [76]: df.columns

Out[76]: Index(['animals', 'age', 'visits'], dtype='object')

In [77]: df.values

Out[77]: array([['cat', 2.0, 1],

['dog', 2.5, 2],

['cat', nan, 3],

['dog', 4.5, 2],

['snake', 3.0, 1]], dtype=object)

In [78]: df.describe() # see statistical data for dat aframe

Out[78]:
age visits

count 4.000000 5.00000

mean 3.000000 1.80000

std 1.080123 0.83666

min 2.000000 1.00000

25% 2.375000 1.00000

50% 2.750000 2.00000

75% 3.375000 2.00000

max 4.500000 3.00000


In [79]: df.sort_values(by='age')

Out[79]:
animals age visits

a cat 2.0 1

b dog 2.5 2

e snake 3.0 1

d dog 4.5 2

c cat NaN 3

In [80]: df[1:3]

Out[80]:
animals age visits

b dog 2.5 2

c cat NaN 3

In [81]: df.sort_values(by='age')[1:3]

Out[81]:
animals age visits

b dog 2.5 2

e snake 3.0 1

In [82]: df[['age','visits']]

Out[82]:
age visits

a 2.0 1

b 2.5 2

c NaN 3

d 4.5 2

e 3.0 1

In [83]: df[2:4]

Out[83]:
animals age visits

c cat NaN 3

d dog 4.5 2
In [84]: df[2:3]

Out[84]:
animals age visits

c cat NaN 3

In [85]: df1=df.copy()
df1

Out[85]:
animals age visits

a cat 2.0 1

b dog 2.5 2

c cat NaN 3

d dog 4.5 2

e snake 3.0 1

In [86]: df1.isnull()

Out[86]:
animals age visits

a False False False

b False False False

c False True False

d False False False

e False False False

In [87]: df1['d','age'] = 1.5

In [88]: df1

Out[88]:
animals age visits (d, age)

a cat 2.0 1 1.5

b dog 2.5 2 1.5

c cat NaN 3 1.5

d dog 4.5 2 1.5

e snake 3.0 1 1.5


In [89]: df1.mean()

C:\Users\HP\AppData\Local\Temp\ipykernel_9568\2053335143.py:1: FutureWarning: T
he default value of numeric_only in DataFrame.mean is deprecated. In a future v
ersion, it will default to False. In addition, specifying 'numeric_only=None' i
s deprecated. Select only valid columns or specify the value of numeric_only to
silence this warning.

df1.mean()

Out[89]: age 3.0

visits 1.8

(d, age) 1.5

dtype: float64

In [90]: df1['visits'].sum()

Out[90]: 9

In [91]: df.sum()

Out[91]: animals catdogcatdogsnake

age 12.0

visits 9

dtype: object

In [92]: string = pd.Series(['a','b','c','d'])


string.str.upper()

Out[92]: 0 A

1 B

2 C

3 D

dtype: object

In [93]: data = {'animals':['cat','dog','cat','dog','snake'],


'age':[2,2.5,np.nan,4.5,3],
'visits':[1,2,3,2,1]}
labels= ['a','b','c','d','e']
df2 = pd.DataFrame(data, index = labels)
df2

Out[93]:
animals age visits

a cat 2.0 1

b dog 2.5 2

c cat NaN 3

d dog 4.5 2

e snake 3.0 1
In [94]: df3 = df2.copy()
df3

Out[94]:
animals age visits

a cat 2.0 1

b dog 2.5 2

c cat NaN 3

d dog 4.5 2

e snake 3.0 1

In [95]: df3['age'].mean()
df3.fillna(4)

Out[95]:
animals age visits

a cat 2.0 1

b dog 2.5 2

c cat 4.0 3

d dog 4.5 2

e snake 3.0 1

In [96]: meanage = df3['age'].mean()


meanage
df3.fillna(meanage)

Out[96]:
animals age visits

a cat 2.0 1

b dog 2.5 2

c cat 3.0 3

d dog 4.5 2

e snake 3.0 1
In [97]: df4 = df3.copy()
df4

Out[97]:
animals age visits

a cat 2.0 1

b dog 2.5 2

c cat NaN 3

d dog 4.5 2

e snake 3.0 1

In [98]: df4.dropna(how="any")

Out[98]:
animals age visits

a cat 2.0 1

b dog 2.5 2

d dog 4.5 2

e snake 3.0 1

In [99]: df4.to_csv('animal.csv')

In [100]: df_animal =pd.read_csv('animal.csv')


df_animal.head(3)

Out[100]:
Unnamed: 0 animals age visits

0 a cat 2.0 1

1 b dog 2.5 2

2 c cat NaN 3
In [101]: df4.to_excel('animal.xlsx',)

---------------------------------------------------------------------------

ModuleNotFoundError Traceback (most recent call last)

Cell In [101], line 1

----> 1 df4.to_excel('animal.xlsx',)

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\util\_d
ecorators.py:211, in deprecate_kwarg.<locals>._deprecate_kwarg.<locals>.wrapper
(*args, **kwargs)

209 else:

210 kwargs[new_arg_name] = new_arg_value

--> 211 return func(*args, **kwargs)

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\util\_d
ecorators.py:211, in deprecate_kwarg.<locals>._deprecate_kwarg.<locals>.wrapper
(*args, **kwargs)

209 else:

210 kwargs[new_arg_name] = new_arg_value

--> 211 return func(*args, **kwargs)

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\core\ge
neric.py:2374, in NDFrame.to_excel(self, excel_writer, sheet_name, na_rep, floa
t_format, columns, header, index, index_label, startrow, startcol, engine, merg
e_cells, encoding, inf_rep, verbose, freeze_panes, storage_options)

2361 from pandas.io.formats.excel import ExcelFormatter

2363 formatter = ExcelFormatter(

2364 df,

2365 na_rep=na_rep,

(...)

2372 inf_rep=inf_rep,

2373 )

-> 2374 formatter.write(

2375 excel_writer,

2376 sheet_name=sheet_name,

2377 startrow=startrow,

2378 startcol=startcol,

2379 freeze_panes=freeze_panes,

2380 engine=engine,

2381 storage_options=storage_options,

2382 )

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\form
ats\excel.py:910, in ExcelFormatter.write(self, writer, sheet_name, startrow, s
tartcol, freeze_panes, engine, storage_options)

906 need_save = False

907 else:

908 # error: Cannot instantiate abstract class 'ExcelWriter' with abstr


act

909 # attributes 'engine', 'save', 'supported_extensions' and 'write_ce


lls'

--> 910 writer = ExcelWriter( # type: ignore[abstract]

911 writer, engine=engine, storage_options=storage_options

912 )

913 need_save = True

915 try:

File ~\AppData\Local\Programs\Python\Python310\lib\site-packages\pandas\io\exce
l\_openpyxl.py:56, in OpenpyxlWriter.__init__(self, path, engine, date_format,
datetime_format, mode, storage_options, if_sheet_exists, engine_kwargs, **kwar
gs)

43 def __init__(

44 self,

45 path: FilePath | WriteExcelBuffer | ExcelWriter,

(...)

54 ) -> None:

55 # Use the openpyxl module as the Excel writer.

---> 56 from openpyxl.workbook import Workbook

58 engine_kwargs = combine_kwargs(engine_kwargs, kwargs)

60 super().__init__(

61 path,

62 mode=mode,

(...)

65 engine_kwargs=engine_kwargs,

66 )

ModuleNotFoundError: No module named 'openpyxl'

In [102]: print(np.char.center('hello',20,fillchar='-'))

-------hello--------

In [103]: a=np.arange(9)
a

Out[103]: array([0, 1, 2, 3, 4, 5, 6, 7, 8])

In [104]: a[5]

Out[104]: 5

In [105]: b=slice([2,8,2])
b

Out[105]: slice(None, [2, 8, 2], None)


In [109]: a = int(input())
b=2
c=0
while b<a:
if a%b==0:
c=1
b+=1
if c==1:
print("comp")
else:
print("prime")

prime

In [*]: data=[]
a=int(input("Enter the no of element "))
print("enter the no in array")
for i in range(int(a)):
n=input("num")
data.append(n)
print(data)
data.reverse()
print(data)

Enter the no of element 7

enter the no in array

num

num

num

num

num

num

num

In [*]: s="abcd1234"[:: -1]


s

In [*]: n = 20
def factorial(n):
if n == 1:
return n
else:
return n*factorial(n-1)
factorial(n)

In [ ]: ​

You might also like