. Pandas

[1]:
1
import pandas as pd
[2]:
1234
# Creating a pandas series from a list 
var=pd.Series([1,2,2,3,4,5])
print(type(var))
print(var)
stdout
<class 'pandas.core.series.Series'> 0 1 1 2 2 2 3 3 4 4 5 5 dtype: int64
[3]:
1234
# Creating a pandas data frame from list
var = pd.DataFrame([1,2,3,4,5])
print(type(var))
print(var)# notice that default column name will be 0 
stdout
<class 'pandas.core.frame.DataFrame'> 0 0 1 1 2 2 3 3 4 4 5
[4]:
1234
# Creating a pandas data frame from list with column name
var = pd.DataFrame([1,2,3,4,5],columns=['sample'])
print(type(var))
print(var)# column name is now changed to sample
stdout
<class 'pandas.core.frame.DataFrame'> sample 0 1 1 2 2 3 3 4 4 5
[5]:
1234
# Creating a pandas data frame from list with column name
var = pd.DataFrame([1,2,3,4,5],columns=['sample'])
print(type(var))
print(var)# column name is now changed to sample
stdout
<class 'pandas.core.frame.DataFrame'> sample 0 1 1 2 2 3 3 4 4 5
[6]:
1234
# Creating an empty data frame in python
var = pd.DataFrame()
print(type(var))
print(var)
stdout
<class 'pandas.core.frame.DataFrame'> Empty DataFrame Columns: [] Index: []
[7]:
123456
# Creating a data frame from dict
var_list1=[25,26,30,21,22,24]
var_list2=['p1','p2','p3','p4','p5','v6'] # the length of the array should be equal here
var_dict={'age':var_list1,'name':var_list2}
df=pd.DataFrame(var_dict)
df
age name
0 25 p1
1 26 p2
2 30 p3
3 21 p4
4 22 p5
5 24 v6
[8]:
1234567
import random
var1=[random.randint(1,100) for x in range(1000)]
var2=[random.randint(1,100) for x in range(1000)]
var3=[random.randint(1,100) for x in range(1000)]
var4=[random.choice(['hello','world','python','is','the','best']) for x in range(1000)]

df=pd.DataFrame({'c1':var1,'c2':var2,'c3':var3,'c4':var4})
[9]:
12
# see top n rows of a df
df.head() # by default it is 5 rows 
c1 c2 c3 c4
0 25 12 92 world
1 81 15 94 python
2 92 54 65 hello
3 42 60 29 is
4 13 54 80 python
[10]:
1
df.head(10) # if value is passed it will shoe that many number of rows
c1 c2 c3 c4
0 25 12 92 world
1 81 15 94 python
2 92 54 65 hello
3 42 60 29 is
4 13 54 80 python
5 19 16 1 python
6 26 7 16 hello
7 96 52 59 the
8 84 62 58 the
9 5 96 49 world
[11]:
1
df.tail() # show last 5 rows 
c1 c2 c3 c4
995 43 69 31 the
996 10 44 85 best
997 61 58 44 hello
998 66 83 87 world
999 64 69 95 the
[12]:
1
df.info() # show infor about null values and data type of a columns
stdout
<class 'pandas.core.frame.DataFrame'> RangeIndex: 1000 entries, 0 to 999 Data columns (total 4 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 c1 1000 non-null int64 1 c2 1000 non-null int64 2 c3 1000 non-null int64 3 c4 1000 non-null object dtypes: int64(3), object(1) memory usage: 31.4+ KB
[13]:
1
df.describe() # returns details about numeric columns 
c1 c2 c3
count 1000.000000 1000.000000 1000.000000
mean 49.841000 51.114000 50.473000
std 28.910267 28.644048 28.368046
min 1.000000 1.000000 1.000000
25% 25.000000 25.750000 26.000000
50% 51.000000 53.500000 52.000000
75% 74.000000 75.250000 74.000000
max 100.000000 100.000000 100.000000
[14]:
123
# selecting 1 column as series 
print(type(df['c1']))
print(df['c1'])
stdout
<class 'pandas.core.series.Series'> 0 25 1 81 2 92 3 42 4 13 .. 995 43 996 10 997 61 998 66 999 64 Name: c1, Length: 1000, dtype: int64
[15]:
123
# selecting 1 column as dataframe 
print(type(df[['c1']]))
df[['c1']]
stdout
<class 'pandas.core.frame.DataFrame'>
c1
0 25
1 81
2 92
3 42
4 13
... ...
995 43
996 10
997 61
998 66
999 64

1000 rows × 1 columns

[16]:
12
# selecting multiple columns 
df[['c1','c2']]
c1 c2
0 25 12
1 81 15
2 92 54
3 42 60
4 13 54
... ... ...
995 43 69
996 10 44
997 61 58
998 66 83
999 64 69

1000 rows × 2 columns

[17]:
1234
# dropping a columns in python
print(df.head())
df.drop(['c2'],axis=1,inplace=True)
df.head()
stdout
c1 c2 c3 c4 0 25 12 92 world 1 81 15 94 python 2 92 54 65 hello 3 42 60 29 is 4 13 54 80 python
c1 c3 c4
0 25 92 world
1 81 94 python
2 92 65 hello
3 42 29 is
4 13 80 python
[18]:
12
# list all the columns in a dataframe
df.columns
Out[18]:
Index(['c1', 'c3', 'c4'], dtype='object')
[19]:
123456
# accessing columns and rows using loc
print(df.loc[1:5,'c1']) # columns c1 rows 1 to 5 
print(df.loc[:,'c1']) # all rows of columns c1
df.loc[1,:] # only 1 row with all columns

stdout
1 81 2 92 3 42 4 13 5 19 Name: c1, dtype: int64 0 25 1 81 2 92 3 42 4 13 .. 995 43 996 10 997 61 998 66 999 64 Name: c1, Length: 1000, dtype: int64
Out[19]:
c1 81 c3 94 c4 python Name: 1, dtype: object
[20]:
12
# accessing columns and rows using iloc, columns and rows both are accessed by index only
df.iloc[1:5,1] # columns with index 1 ,rows 1 to 5 
Out[20]:
1 94 2 65 3 29 4 80 Name: c3, dtype: int64
[21]:
123456
# creating a sample dataframe
var1=[random.randint(1,100) for x in range(1000)]
var2=[random.randint(1,100) for x in range(1000)]
var3=[random.randint(1,100) for x in range(1000)]
var4=[random.choice(['hello','world','python','is','the','best']) for x in range(1000)]
df=pd.DataFrame({'c1':var1,'c2':var2,'c3':var3,'c4':var4})
[22]:
123
# accessing the indexes of a dataframe 
print(df.index) # range element
print(list(df.index)) # converting index to list
stdout
RangeIndex(start=0, stop=1000, step=1) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266, 267, 268, 269, 270, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280, 281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336, 337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475, 476, 477, 478, 479, 480, 481, 482, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 527, 528, 529, 530, 531, 532, 533, 534, 535, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 548, 549, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 598, 599, 600, 601, 602, 603, 604, 605, 606, 607, 608, 609, 610, 611, 612, 613, 614, 615, 616, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732, 733, 734, 735, 736, 737, 738, 739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 795, 796, 797, 798, 799, 800, 801, 802, 803, 804, 805, 806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 862, 863, 864, 865, 866, 867, 868, 869, 870, 871, 872, 873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 929, 930, 931, 932, 933, 934, 935, 936, 937, 938, 939, 940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 996, 997, 998, 999]
[23]:
1234
# setting a column as index
print(df.head())
df.set_index(['c1'],inplace=True)
stdout
c1 c2 c3 c4 0 15 30 33 world 1 83 53 91 python 2 81 7 53 the 3 62 1 63 hello 4 38 65 73 the
[24]:
1
df
c2 c3 c4
c1
15 30 33 world
83 53 91 python
81 7 53 the
62 1 63 hello
38 65 73 the
... ... ... ...
48 6 70 the
33 41 49 the
98 38 31 world
63 19 56 best
29 90 83 hello

1000 rows × 3 columns

[25]:
1
df.loc[10,:]  # accessing all rows with index 10 
c2 c3 c4
c1
10 32 41 python
10 84 38 is
10 78 55 world
10 32 46 is
10 47 84 the
10 27 2 python
10 80 49 hello
10 88 80 the
10 100 54 the
10 1 66 is
10 6 72 python
10 29 80 python
[26]:
123
# reading data from a csv file
df=pd.read_csv('./data/fifa_eda.csv') # reading fifa data this file is saved in my current directory/data folder
df.head()
ID Name Age Nationality Overall Potential Club Value Wage Preferred Foot International Reputation Skill Moves Position Joined Contract Valid Until Height Weight Release Clause
0 158023 L. Messi 31 Argentina 94 94 FC Barcelona 110500.0 565.0 Left 5.0 4.0 RF 2004 2021-01-01 5.583333 159.0 226500.0
1 20801 Cristiano Ronaldo 33 Portugal 94 94 Juventus 77000.0 405.0 Right 5.0 5.0 ST 2018 2022-01-01 6.166667 183.0 127100.0
2 190871 Neymar Jr 26 Brazil 92 93 Paris Saint-Germain 118500.0 290.0 Right 5.0 5.0 LW 2017 2022-01-01 5.750000 150.0 228100.0
3 193080 De Gea 27 Spain 91 93 Manchester United 72000.0 260.0 Right 4.0 1.0 GK 2011 2020-01-01 6.333333 168.0 138600.0
4 192985 K. De Bruyne 27 Belgium 91 92 Manchester City 102000.0 355.0 Right 4.0 4.0 RCM 2015 2023-01-01 5.916667 154.0 196400.0
[ ]:
1234567
# count all the categories 
count_dict={}
count_dict['high']=0
count_dict['low']=0
count_dict['medium']=0
for i in df['wage_category']:
    count_dict[i]=count_dict[i]+1
[27]:
1234
# performing basic EDA on this data
print(f"The data has {df.shape[0]} rows and {df.shape[1]} columns")
# null values check
df.info()
stdout
The data has 18207 rows and 18 columns <class 'pandas.core.frame.DataFrame'> RangeIndex: 18207 entries, 0 to 18206 Data columns (total 18 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 ID 18207 non-null int64 1 Name 18207 non-null object 2 Age 18207 non-null int64 3 Nationality 18207 non-null object 4 Overall 18207 non-null int64 5 Potential 18207 non-null int64 6 Club 17966 non-null object 7 Value 17955 non-null float64 8 Wage 18207 non-null float64 9 Preferred Foot 18207 non-null object 10 International Reputation 18159 non-null float64 11 Skill Moves 18159 non-null float64 12 Position 18207 non-null object 13 Joined 18207 non-null int64 14 Contract Valid Until 17918 non-null object 15 Height 18207 non-null float64 16 Weight 18207 non-null float64 17 Release Clause 18207 non-null float64 dtypes: float64(7), int64(5), object(6) memory usage: 2.5+ MB
[28]:
12
# numeric values check 
df.describe()
ID Age Overall Potential Value Wage International Reputation Skill Moves Joined Height Weight Release Clause
count 18207.000000 18207.000000 18207.000000 18207.000000 17955.000000 18207.000000 18159.000000 18159.000000 18207.000000 18207.000000 18207.000000 18207.000000
mean 214298.338606 25.122206 66.238699 71.307299 2444.530214 9.731312 1.113222 2.361308 2016.420607 5.946771 165.979129 4585.060971
std 29965.244204 4.669943 6.908930 6.136496 5626.715434 21.999290 0.394031 0.756164 2.018194 0.220514 15.572775 10630.414430
min 16.000000 16.000000 46.000000 48.000000 10.000000 0.000000 1.000000 1.000000 1991.000000 5.083333 110.000000 13.000000
25% 200315.500000 21.000000 62.000000 67.000000 325.000000 1.000000 1.000000 2.000000 2016.000000 5.750000 154.000000 570.000000
50% 221759.000000 25.000000 66.000000 71.000000 700.000000 3.000000 1.000000 2.000000 2017.000000 5.916667 165.000000 1300.000000
75% 236529.500000 28.000000 71.000000 75.000000 2100.000000 9.000000 1.000000 3.000000 2018.000000 6.083333 176.000000 4585.060806
max 246620.000000 45.000000 94.000000 95.000000 118500.000000 565.000000 5.000000 5.000000 2018.000000 6.750000 243.000000 228100.000000
[29]:
123
df['c5']='abc' # this will add a constant value 'abc' to each row 
df['c6']=[random.randint(1,10) for x in range(df.shape[0])] # using a list to add a column 
df
ID Name Age Nationality Overall Potential Club Value Wage Preferred Foot International Reputation Skill Moves Position Joined Contract Valid Until Height Weight Release Clause c5 c6
0 158023 L. Messi 31 Argentina 94 94 FC Barcelona 110500.0 565.0 Left 5.0 4.0 RF 2004 2021-01-01 5.583333 159.0 226500.0 abc 4
1 20801 Cristiano Ronaldo 33 Portugal 94 94 Juventus 77000.0 405.0 Right 5.0 5.0 ST 2018 2022-01-01 6.166667 183.0 127100.0 abc 10
2 190871 Neymar Jr 26 Brazil 92 93 Paris Saint-Germain 118500.0 290.0 Right 5.0 5.0 LW 2017 2022-01-01 5.750000 150.0 228100.0 abc 4
3 193080 De Gea 27 Spain 91 93 Manchester United 72000.0 260.0 Right 4.0 1.0 GK 2011 2020-01-01 6.333333 168.0 138600.0 abc 2
4 192985 K. De Bruyne 27 Belgium 91 92 Manchester City 102000.0 355.0 Right 4.0 4.0 RCM 2015 2023-01-01 5.916667 154.0 196400.0 abc 4
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
18202 238813 J. Lundstram 19 England 47 65 Crewe Alexandra 60.0 1.0 Right 1.0 2.0 CM 2017 2019-01-01 5.750000 134.0 143.0 abc 9
18203 243165 N. Christoffersson 19 Sweden 47 63 Trelleborgs FF 60.0 1.0 Right 1.0 2.0 ST 2018 2020-01-01 6.250000 170.0 113.0 abc 3
18204 241638 B. Worman 16 England 47 67 Cambridge United 60.0 1.0 Right 1.0 2.0 ST 2017 2021-01-01 5.666667 148.0 165.0 abc 8
18205 246268 D. Walker-Rice 17 England 47 66 Tranmere Rovers 60.0 1.0 Right 1.0 2.0 RW 2018 2019-01-01 5.833333 154.0 143.0 abc 9
18206 246269 G. Nugent 16 England 46 66 Tranmere Rovers 60.0 1.0 Right 1.0 2.0 CM 2018 2019-01-01 5.833333 176.0 165.0 abc 2

18207 rows × 20 columns

[30]:
1
df.drop(['c5','c6'],axis=1,inplace=True) # dropping above 2 columns as they are not required for our anlaysis
[31]:
123456789101112131415
# create a function which return 3 values 'low','medium' and 'high' under following conditions 
# low - if Wage is below 3
# medium - if Wage is between 3 and 9 inclusice 
# high - if Wage is above 9
def wage_category(wage):
    if wage<3:
        return 'low'
    elif wage>=3 and wage<=9:
        return 'medium'
    else:
        return 'high'
wage_series=df['Wage'].apply(wage_category) # it will return a pandas series with length equal to number of rows in data frame
# this can now be assigned as a columns of the dataframe
df['wage_category']=wage_series
df.head()
ID Name Age Nationality Overall Potential Club Value Wage Preferred Foot International Reputation Skill Moves Position Joined Contract Valid Until Height Weight Release Clause wage_category
0 158023 L. Messi 31 Argentina 94 94 FC Barcelona 110500.0 565.0 Left 5.0 4.0 RF 2004 2021-01-01 5.583333 159.0 226500.0 high
1 20801 Cristiano Ronaldo 33 Portugal 94 94 Juventus 77000.0 405.0 Right 5.0 5.0 ST 2018 2022-01-01 6.166667 183.0 127100.0 high
2 190871 Neymar Jr 26 Brazil 92 93 Paris Saint-Germain 118500.0 290.0 Right 5.0 5.0 LW 2017 2022-01-01 5.750000 150.0 228100.0 high
3 193080 De Gea 27 Spain 91 93 Manchester United 72000.0 260.0 Right 4.0 1.0 GK 2011 2020-01-01 6.333333 168.0 138600.0 high
4 192985 K. De Bruyne 27 Belgium 91 92 Manchester City 102000.0 355.0 Right 4.0 4.0 RCM 2015 2023-01-01 5.916667 154.0 196400.0 high
[32]:
123
# using lambda function with apply function , this works row wise 
# add column value and wage using apply and lambda 
df.apply(lambda row:row['Value']+row['Wage'],axis=1)
Out[32]:
0 111065.0 1 77405.0 2 118790.0 3 72260.0 4 102355.0 ... 18202 61.0 18203 61.0 18204 61.0 18205 61.0 18206 61.0 Length: 18207, dtype: float64
[33]:
1234567
 
# +,-,/,* between two numeric columns 
df['new_col']=df['Value']+df['Wage']
df['new_col']=df['Value']-df['Wage']
df['new_col']=df['Value']*df['Wage']
df['new_col']=df['Value']/df['Wage']
df.head()
ID Name Age Nationality Overall Potential Club Value Wage Preferred Foot International Reputation Skill Moves Position Joined Contract Valid Until Height Weight Release Clause wage_category new_col
0 158023 L. Messi 31 Argentina 94 94 FC Barcelona 110500.0 565.0 Left 5.0 4.0 RF 2004 2021-01-01 5.583333 159.0 226500.0 high 195.575221
1 20801 Cristiano Ronaldo 33 Portugal 94 94 Juventus 77000.0 405.0 Right 5.0 5.0 ST 2018 2022-01-01 6.166667 183.0 127100.0 high 190.123457
2 190871 Neymar Jr 26 Brazil 92 93 Paris Saint-Germain 118500.0 290.0 Right 5.0 5.0 LW 2017 2022-01-01 5.750000 150.0 228100.0 high 408.620690
3 193080 De Gea 27 Spain 91 93 Manchester United 72000.0 260.0 Right 4.0 1.0 GK 2011 2020-01-01 6.333333 168.0 138600.0 high 276.923077
4 192985 K. De Bruyne 27 Belgium 91 92 Manchester City 102000.0 355.0 Right 4.0 4.0 RCM 2015 2023-01-01 5.916667 154.0 196400.0 high 287.323944
[34]:
1
df.drop(['new_col'],axis=1,inplace=True)
[35]:
123
# + with 2 non numeric columns 
df['new_col']=df['Name']+' '+df['Nationality'] # it will concat all the string values 
df.head()
ID Name Age Nationality Overall Potential Club Value Wage Preferred Foot International Reputation Skill Moves Position Joined Contract Valid Until Height Weight Release Clause wage_category new_col
0 158023 L. Messi 31 Argentina 94 94 FC Barcelona 110500.0 565.0 Left 5.0 4.0 RF 2004 2021-01-01 5.583333 159.0 226500.0 high L. Messi Argentina
1 20801 Cristiano Ronaldo 33 Portugal 94 94 Juventus 77000.0 405.0 Right 5.0 5.0 ST 2018 2022-01-01 6.166667 183.0 127100.0 high Cristiano Ronaldo Portugal
2 190871 Neymar Jr 26 Brazil 92 93 Paris Saint-Germain 118500.0 290.0 Right 5.0 5.0 LW 2017 2022-01-01 5.750000 150.0 228100.0 high Neymar Jr Brazil
3 193080 De Gea 27 Spain 91 93 Manchester United 72000.0 260.0 Right 4.0 1.0 GK 2011 2020-01-01 6.333333 168.0 138600.0 high De Gea Spain
4 192985 K. De Bruyne 27 Belgium 91 92 Manchester City 102000.0 355.0 Right 4.0 4.0 RCM 2015 2023-01-01 5.916667 154.0 196400.0 high K. De Bruyne Belgium
[36]:
1
df.drop(['new_col'],axis=1,inplace=True)
[37]:
123456
# constanct value with columns
df['new_col']=df['Value']*2
df['new_col']=df['Value']+2
df['new_col']=df['Value']-2
df['new_col']=df['Value']/2
df.head()
ID Name Age Nationality Overall Potential Club Value Wage Preferred Foot International Reputation Skill Moves Position Joined Contract Valid Until Height Weight Release Clause wage_category new_col
0 158023 L. Messi 31 Argentina 94 94 FC Barcelona 110500.0 565.0 Left 5.0 4.0 RF 2004 2021-01-01 5.583333 159.0 226500.0 high 55250.0
1 20801 Cristiano Ronaldo 33 Portugal 94 94 Juventus 77000.0 405.0 Right 5.0 5.0 ST 2018 2022-01-01 6.166667 183.0 127100.0 high 38500.0
2 190871 Neymar Jr 26 Brazil 92 93 Paris Saint-Germain 118500.0 290.0 Right 5.0 5.0 LW 2017 2022-01-01 5.750000 150.0 228100.0 high 59250.0
3 193080 De Gea 27 Spain 91 93 Manchester United 72000.0 260.0 Right 4.0 1.0 GK 2011 2020-01-01 6.333333 168.0 138600.0 high 36000.0
4 192985 K. De Bruyne 27 Belgium 91 92 Manchester City 102000.0 355.0 Right 4.0 4.0 RCM 2015 2023-01-01 5.916667 154.0 196400.0 high 51000.0
[38]:
1
df.drop(['new_col'],axis=1,inplace=True)
[39]:
12345
# sum,avg,min ,max rows wise 
print(df['Wage'].mean())
print(df['Wage'].min())
print(df['Wage'].max())
print(df['Wage'].sum())
stdout
9.731312132696216 0.0 565.0 177178.0
[40]:
12
# value counts function 
df['Wage'].value_counts()
Out[40]:
1.0 4900 2.0 2827 3.0 1857 4.0 1255 5.0 869 ... 455.0 1 265.0 1 250.0 1 300.0 1 565.0 1 Name: Wage, Length: 144, dtype: int64
[41]:
12
# drop function can be used to delete rows also from a data from using index and axis 
df.drop([0,1],axis=0) # not writing inplace here as we donot want to drop it from table 
ID Name Age Nationality Overall Potential Club Value Wage Preferred Foot International Reputation Skill Moves Position Joined Contract Valid Until Height Weight Release Clause wage_category
2 190871 Neymar Jr 26 Brazil 92 93 Paris Saint-Germain 118500.0 290.0 Right 5.0 5.0 LW 2017 2022-01-01 5.750000 150.0 228100.0 high
3 193080 De Gea 27 Spain 91 93 Manchester United 72000.0 260.0 Right 4.0 1.0 GK 2011 2020-01-01 6.333333 168.0 138600.0 high
4 192985 K. De Bruyne 27 Belgium 91 92 Manchester City 102000.0 355.0 Right 4.0 4.0 RCM 2015 2023-01-01 5.916667 154.0 196400.0 high
5 183277 E. Hazard 27 Belgium 91 91 Chelsea 93000.0 340.0 Right 4.0 4.0 LF 2012 2020-01-01 5.666667 163.0 172100.0 high
6 177003 L. Modrić 32 Croatia 91 91 Real Madrid 67000.0 420.0 Right 4.0 4.0 RCM 2012 2020-01-01 5.666667 146.0 137400.0 high
... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ... ...
18202 238813 J. Lundstram 19 England 47 65 Crewe Alexandra 60.0 1.0 Right 1.0 2.0 CM 2017 2019-01-01 5.750000 134.0 143.0 low
18203 243165 N. Christoffersson 19 Sweden 47 63 Trelleborgs FF 60.0 1.0 Right 1.0 2.0 ST 2018 2020-01-01 6.250000 170.0 113.0 low
18204 241638 B. Worman 16 England 47 67 Cambridge United 60.0 1.0 Right 1.0 2.0 ST 2017 2021-01-01 5.666667 148.0 165.0 low
18205 246268 D. Walker-Rice 17 England 47 66 Tranmere Rovers 60.0 1.0 Right 1.0 2.0 RW 2018 2019-01-01 5.833333 154.0 143.0 low
18206 246269 G. Nugent 16 England 46 66 Tranmere Rovers 60.0 1.0 Right 1.0 2.0 CM 2018 2019-01-01 5.833333 176.0 165.0 low

18205 rows × 19 columns

[42]:
1234
# iterrows() return 1 variable for index and 1 variable for row 
for i,j in df.head(2).iterrows():
    print("i--->",i)
    print("j--->",j)
stdout
i---> 0 j---> ID 158023 Name L. Messi Age 31 Nationality Argentina Overall 94 Potential 94 Club FC Barcelona Value 110500.0 Wage 565.0 Preferred Foot Left International Reputation 5.0 Skill Moves 4.0 Position RF Joined 2004 Contract Valid Until 2021-01-01 Height 5.583333 Weight 159.0 Release Clause 226500.0 wage_category high Name: 0, dtype: object i---> 1 j---> ID 20801 Name Cristiano Ronaldo Age 33 Nationality Portugal Overall 94 Potential 94 Club Juventus Value 77000.0 Wage 405.0 Preferred Foot Right International Reputation 5.0 Skill Moves 5.0 Position ST Joined 2018 Contract Valid Until 2022-01-01 Height 6.166667 Weight 183.0 Release Clause 127100.0 wage_category high Name: 1, dtype: object
[43]:
1234
# iterrows() - indivial col value of rows can also be accesed
for i,j in df.head(2).iterrows():
    print("i--->",i)
    print("j--->",j['Wage'],j['Value'])
stdout
i---> 0 j---> 565.0 110500.0 i---> 1 j---> 405.0 77000.0
[46]:
12345
# iteritems - return rows and key value pair 
# iterrows() - indivial col value of rows can also be accesed
for i,j in df.head(2).iteritems():
    print("i--->",i) # i will be columns name here
    print("j--->",j) # values will be value of that column 
stdout
i---> ID j---> 0 158023 1 20801 Name: ID, dtype: int64 i---> Name j---> 0 L. Messi 1 Cristiano Ronaldo Name: Name, dtype: object i---> Age j---> 0 31 1 33 Name: Age, dtype: int64 i---> Nationality j---> 0 Argentina 1 Portugal Name: Nationality, dtype: object i---> Overall j---> 0 94 1 94 Name: Overall, dtype: int64 i---> Potential j---> 0 94 1 94 Name: Potential, dtype: int64 i---> Club j---> 0 FC Barcelona 1 Juventus Name: Club, dtype: object i---> Value j---> 0 110500.0 1 77000.0 Name: Value, dtype: float64 i---> Wage j---> 0 565.0 1 405.0 Name: Wage, dtype: float64 i---> Preferred Foot j---> 0 Left 1 Right Name: Preferred Foot, dtype: object i---> International Reputation j---> 0 5.0 1 5.0 Name: International Reputation, dtype: float64 i---> Skill Moves j---> 0 4.0 1 5.0 Name: Skill Moves, dtype: float64 i---> Position j---> 0 RF 1 ST Name: Position, dtype: object i---> Joined j---> 0 2004 1 2018 Name: Joined, dtype: int64 i---> Contract Valid Until j---> 0 2021-01-01 1 2022-01-01 Name: Contract Valid Until, dtype: object i---> Height j---> 0 5.583333 1 6.166667 Name: Height, dtype: float64 i---> Weight j---> 0 159.0 1 183.0 Name: Weight, dtype: float64 i---> Release Clause j---> 0 226500.0 1 127100.0 Name: Release Clause, dtype: float64 i---> wage_category j---> 0 high 1 high Name: wage_category, dtype: object
[50]:
123
# itertuples - 
for i in df.head(2).itertuples():
    print(i)
stdout
Pandas(Index=0, ID=158023, Name='L. Messi', Age=31, Nationality='Argentina', Overall=94, Potential=94, Club='FC Barcelona', Value=110500.0, Wage=565.0, _10='Left', _11=5.0, _12=4.0, Position='RF', Joined=2004, _15='2021-01-01', Height=5.583333333333333, Weight=159.0, _18=226500.0, wage_category='high') Pandas(Index=1, ID=20801, Name='Cristiano Ronaldo', Age=33, Nationality='Portugal', Overall=94, Potential=94, Club='Juventus', Value=77000.0, Wage=405.0, _10='Right', _11=5.0, _12=5.0, Position='ST', Joined=2018, _15='2022-01-01', Height=6.166666666666667, Weight=183.0, _18=127100.0, wage_category='high')
[52]:
1
df.sort_values(by='Wage',inplace=True)
[53]:
1
df.head()
ID Name Age Nationality Overall Potential Club Value Wage Preferred Foot International Reputation Skill Moves Position Joined Contract Valid Until Height Weight Release Clause wage_category
14487 222402 J. Gulley 25 New Zealand 61 64 NaN NaN 0.0 Right 1.0 2.0 RB 2016 NaN 5.750000 154.0 4585.060806 low
2065 177149 B. Jokič 32 Slovenia 75 75 NaN NaN 0.0 Left 1.0 2.0 LB 2016 NaN 5.750000 170.0 4585.060806 low
8057 225882 D. Mendiseca 22 Paraguay 67 67 NaN NaN 0.0 Left 1.0 2.0 LB 2016 NaN 6.000000 174.0 4585.060806 low
15196 245979 A. Tsvetkov 27 Bulgaria 60 61 NaN NaN 0.0 Right 1.0 2.0 CDM 2016 NaN 5.916667 165.0 4585.060806 low
8061 218971 S. Gbohouo 29 Ivory Coast 67 68 NaN NaN 0.0 Right 1.0 1.0 GK 2016 NaN 6.250000 181.0 4585.060806 low
[54]:
12
# grouping data using a column 
df.groupby(['Position'])['Wage'].mean() 
Out[54]:
Position CAM 10.218978 CB 7.700393 CDM 9.315401 CF 10.216216 CM 8.334767 GK 6.797237 LAM 26.142857 LB 8.467930 LCB 11.498457 LCM 14.131646 LDM 11.860082 LF 44.666667 LM 9.656621 LS 15.260870 LW 13.068241 LWB 9.076923 RAM 19.095238 RB 8.604183 RCB 12.688822 RCM 14.404092 RDM 12.149194 RF 52.687500 RM 9.515528 RS 14.379310 RW 14.432432 RWB 8.597701 ST 9.928969 Name: Wage, dtype: float64
[56]:
1
df.groupby(['Position','Preferred Foot'])['Wage'].sum() 
Out[56]:
Position Preferred Foot CAM Left 2849.0 Right 6951.0 CB Left 2939.0 Right 10760.0 CDM Left 938.0 Right 7893.0 CF Left 145.0 Right 611.0 CM Left 2297.0 Right 9330.0 GK Left 2117.0 Right 11661.0 LAM Left 442.0 Right 107.0 LB Left 10500.0 Right 1118.0 LCB Left 3001.0 Right 4450.0 LCM Left 1416.0 Right 4166.0 LDM Left 464.0 Right 2418.0 LF Left 226.0 Right 444.0 LM Left 2881.0 Right 7693.0 LS Left 446.0 Right 2713.0 LW Left 857.0 Right 4122.0 LWB Left 567.0 Right 141.0 RAM Left 120.0 Right 281.0 RB Left 79.0 Right 11029.0 RCB Left 177.0 Right 8223.0 RCM Left 561.0 Right 5071.0 RDM Left 190.0 Right 2823.0 RF Left 602.0 Right 241.0 RM Left 3537.0 Right 7187.0 RS Left 367.0 Right 2552.0 RW Left 2316.0 Right 3024.0 RWB Left 12.0 Right 736.0 ST Left 3531.0 Right 17856.0 Name: Wage, dtype: float64
[60]:
1
df.groupby(['Position','Preferred Foot']).agg({'Wage':'sum','Overall':'mean'}).reset_index().head()
Position Preferred Foot Wage Overall
0 CAM Left 2849.0 68.217899
1 CAM Right 6951.0 66.424501
2 CB Left 2939.0 65.741935
3 CB Right 10760.0 64.854659
4 CDM Left 938.0 66.309524
[62]:
1234
# concat 2 data frames
df1=pd.DataFrame({'c1':[1,2,3],'c2':[1,2,3]})
df2=pd.DataFrame({'c1':[6,7,8],'c2':[1,2,3]})
final_df=pd.concat([df1,df2])
[63]:
1
final_df
c1 c2
0 1 1
1 2 2
2 3 3
0 6 1
1 7 2
2 8 3
[65]:
12345
# concat 2 data frames with different columns 
df1=pd.DataFrame({'c1':[1,2,3],'c2':[1,2,3]})
df2=pd.DataFrame({'c3':[6,7,8],'c2':[1,2,3]})
final_df=pd.concat([df1,df2])
final_df
c1 c2 c3
0 1.0 1 NaN
1 2.0 2 NaN
2 3.0 3 NaN
0 NaN 1 6.0
1 NaN 2 7.0
2 NaN 3 8.0
[70]:
1234
# join two dataframes 
df1=df[['ID','Name','Age','Nationality']]
df2=df[['ID','Wage','Preferred Foot','Position']]
[73]:
12
merged_df=pd.merge(left=df1,right=df2,how='inner',left_on=['ID'],right_on=['ID']) # left ,right,inner ,outer
merged_df.head()
ID Name Age Nationality Wage Preferred Foot Position
0 222402 J. Gulley 25 New Zealand 0.0 Right RB
1 177149 B. Jokič 32 Slovenia 0.0 Left LB
2 225882 D. Mendiseca 22 Paraguay 0.0 Left LB
3 245979 A. Tsvetkov 27 Bulgaria 0.0 Right CDM
4 218971 S. Gbohouo 29 Ivory Coast 0.0 Right GK
[75]:
123
# converting to columns to datetime type 
# notice that "Contract Valid Until" is object type in the datafra,e
df.info()
stdout
<class 'pandas.core.frame.DataFrame'> Int64Index: 18207 entries, 14487 to 0 Data columns (total 19 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 ID 18207 non-null int64 1 Name 18207 non-null object 2 Age 18207 non-null int64 3 Nationality 18207 non-null object 4 Overall 18207 non-null int64 5 Potential 18207 non-null int64 6 Club 17966 non-null object 7 Value 17955 non-null float64 8 Wage 18207 non-null float64 9 Preferred Foot 18207 non-null object 10 International Reputation 18159 non-null float64 11 Skill Moves 18159 non-null float64 12 Position 18207 non-null object 13 Joined 18207 non-null int64 14 Contract Valid Until 17918 non-null object 15 Height 18207 non-null float64 16 Weight 18207 non-null float64 17 Release Clause 18207 non-null float64 18 wage_category 18207 non-null object dtypes: float64(7), int64(5), object(7) memory usage: 2.8+ MB
[ ]:
12345678910111213
# working with date and time in python and pandas 
# python , pandas 
import datetime as dt
sample_var=dt.datetime(year=2024,month=1,day=5,hour=14,minute=55,second=45)
type(sample_var)
# str to date 
sample_str_date='2024-12-31 12:45:45'
dt.datetime.strptime(sample_str_date,'%Y-%m-%d %H:%M:%S')
# str to date 
sample_date=dt.datetime(year=2024,month=1,day=5,hour=14,minute=55,second=45)
dt.datetime.strftime(sample_date,'%Y-%m-%d %H:%M:%S')
# adding n days to date ,n months to date 
sample_date+dt.timedelta(days=12)
[76]:
123
# we will now convert this column to datetime columns 
df['Contract Valid Until']=pd.to_datetime(df['Contract Valid Until'])
df.info()
stdout
<class 'pandas.core.frame.DataFrame'> Int64Index: 18207 entries, 14487 to 0 Data columns (total 19 columns): # Column Non-Null Count Dtype --- ------ -------------- ----- 0 ID 18207 non-null int64 1 Name 18207 non-null object 2 Age 18207 non-null int64 3 Nationality 18207 non-null object 4 Overall 18207 non-null int64 5 Potential 18207 non-null int64 6 Club 17966 non-null object 7 Value 17955 non-null float64 8 Wage 18207 non-null float64 9 Preferred Foot 18207 non-null object 10 International Reputation 18159 non-null float64 11 Skill Moves 18159 non-null float64 12 Position 18207 non-null object 13 Joined 18207 non-null int64 14 Contract Valid Until 17918 non-null datetime64[ns] 15 Height 18207 non-null float64 16 Weight 18207 non-null float64 17 Release Clause 18207 non-null float64 18 wage_category 18207 non-null object dtypes: datetime64[ns](1), float64(7), int64(5), object(6) memory usage: 2.8+ MB
[79]:
12345
# extracting info from datetime column in pandas 
print(pd.DatetimeIndex(df['Contract Valid Until']).hour)
print(pd.DatetimeIndex(df['Contract Valid Until']).minute)
print(pd.DatetimeIndex(df['Contract Valid Until']).day)
stdout
Float64Index([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, ... 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], dtype='float64', name='Contract Valid Until', length=18207) Float64Index([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, ... 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0], dtype='float64', name='Contract Valid Until', length=18207) Float64Index([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, ... 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], dtype='float64', name='Contract Valid Until', length=18207)
[82]:
123
# we can also find out min , max time from a timestamp column and also do a group of them 
print(df['Contract Valid Until'].max())
print(df['Contract Valid Until'].min())
stdout
2026-01-01 00:00:00 2018-01-01 00:00:00
[83]:
12
# subtract n days from datetime column 
df['Contract Valid Until']-pd.DateOffset(days=10)
Out[83]:
14487 NaT 2065 NaT 8057 NaT 15196 NaT 8061 NaT ... 8 2019-12-22 1 2021-12-22 6 2019-12-22 7 2020-12-22 0 2020-12-22 Name: Contract Valid Until, Length: 18207, dtype: datetime64[ns]
[ ]:
123
# convert datetime format for all the values in pandas columns 
[dt.datetime.strftime(x,'%d-%m-%Y') for x in df[~df['Contract Valid Until'].isna()]['Contract Valid Until']]
[91]:
123
# convert a value of columns to upper or lower 
df['Name']=df['Name'].str.upper()# with assignment
df.head()
ID Name Age Nationality Overall Potential Club Value Wage Preferred Foot International Reputation Skill Moves Position Joined Contract Valid Until Height Weight Release Clause wage_category
14487 222402 J. GULLEY 25 New Zealand 61 64 NaN NaN 0.0 Right 1.0 2.0 RB 2016 NaT 5.750000 154.0 4585.060806 low
2065 177149 B. JOKIČ 32 Slovenia 75 75 NaN NaN 0.0 Left 1.0 2.0 LB 2016 NaT 5.750000 170.0 4585.060806 low
8057 225882 D. MENDISECA 22 Paraguay 67 67 NaN NaN 0.0 Left 1.0 2.0 LB 2016 NaT 6.000000 174.0 4585.060806 low
15196 245979 A. TSVETKOV 27 Bulgaria 60 61 NaN NaN 0.0 Right 1.0 2.0 CDM 2016 NaT 5.916667 165.0 4585.060806 low
8061 218971 S. GBOHOUO 29 Ivory Coast 67 68 NaN NaN 0.0 Right 1.0 1.0 GK 2016 NaT 6.250000 181.0 4585.060806 low
[104]:
12
# Splitting basis a seperator
df["Name"].str.split(".")
Out[104]:
14487 [J, GULLEY] 2065 [B, JOKIČ] 8057 [D, MENDISECA] 15196 [A, TSVETKOV] 8061 [S, GBOHOUO] ... 8 [SERGIO RAMOS] 1 [CRISTIANO RONALDO] 6 [L, MODRIĆ] 7 [L, SUÁREZ] 0 [L, MESSI] Name: Name, Length: 18207, dtype: object
[105]:
12
# Splitting basis a seperator and expand option
df["Name"].str.split(".",expand=True)
0 1 2
14487 J GULLEY None
2065 B JOKIČ None
8057 D MENDISECA None
15196 A TSVETKOV None
8061 S GBOHOUO None
... ... ... ...
8 SERGIO RAMOS None None
1 CRISTIANO RONALDO None None
6 L MODRIĆ None
7 L SUÁREZ None
0 L MESSI None

18207 rows × 3 columns

[107]:
12
# replace function 
df["Name"].replace('J. GULLEY','abc')
Out[107]:
14487 abc 2065 B. JOKIČ 8057 D. MENDISECA 15196 A. TSVETKOV 8061 S. GBOHOUO ... 8 SERGIO RAMOS 1 CRISTIANO RONALDO 6 L. MODRIĆ 7 L. SUÁREZ 0 L. MESSI Name: Name, Length: 18207, dtype: object
[ ]:
1