Pandas DataFrame operations
Creating DataFrame
Program
import pandas as pd
#Creating DataFrame
cars = pd.DataFrame({'name':['benz','bmw','tata'], 'showroomprice':[12.5,24.6,10.6], 'onroadprice':[16.8,29.6,14.8]})
print("Cars Information:")
print(cars)
#Creating DataFrame
cars = pd.DataFrame({'name':['benz','bmw','tata'], 'showroomprice':[12.5,24.6,10.6], 'onroadprice':[16.8,29.6,14.8]})
print("Cars Information:")
print(cars)
Output
Cars Information:
name showroomprice onroadprice
0 benz 12.5 16.8
1 bmw 24.6 29.6
2 tata 10.6 14.8
name showroomprice onroadprice
0 benz 12.5 16.8
1 bmw 24.6 29.6
2 tata 10.6 14.8
Concatenate of DataFrames
Program
import pandas as pd
df1 = pd.DataFrame({'r1':[1,2,3],'r2':[4,5,6]})
df2 = pd.DataFrame({'r1':[7,8,9],'r2':[10,11,12]})
df = pd.concat([df1,df2])
print("Concatenated DataFrames")
print(df)
df1 = pd.DataFrame({'r1':[1,2,3],'r2':[4,5,6]})
df2 = pd.DataFrame({'r1':[7,8,9],'r2':[10,11,12]})
df = pd.concat([df1,df2])
print("Concatenated DataFrames")
print(df)
Output
Concatenated DataFrames
r1 r2
0 1 4
1 2 5
2 3 6
0 7 10
1 8 11
2 9 12
r1 r2
0 1 4
1 2 5
2 3 6
0 7 10
1 8 11
2 9 12
Setting Conditions
Program
import pandas as pd
df = pd.DataFrame(range(1,21))
col1 = df.loc[df[0]%3==0]
print("DataDrame first column elements that are divisible by 3")
print(col1)
df = pd.DataFrame(range(1,21))
col1 = df.loc[df[0]%3==0]
print("DataDrame first column elements that are divisible by 3")
print(col1)
Output
DataDrame first column elements that are divisible by 3
0
2 3
5 6
8 9
11 12
14 15
17 18
0
2 3
5 6
8 9
11 12
14 15
17 18
Adding a New Column
Program
import pandas as pd
#Creating DataFrame
cars = pd.DataFrame({'name':['benz','bmw','tata'], 'showroomprice':[12.5,24.6,10.6] })
print("Car Details:")
print(cars)
cars.insert(2,'onroadprice',[16.8,29.6,14.8],True)
print("After adding onroadprice column, Car Details:")
print(cars)
#Creating DataFrame
cars = pd.DataFrame({'name':['benz','bmw','tata'], 'showroomprice':[12.5,24.6,10.6] })
print("Car Details:")
print(cars)
cars.insert(2,'onroadprice',[16.8,29.6,14.8],True)
print("After adding onroadprice column, Car Details:")
print(cars)
Output
Car Details:
name showroomprice
0 benz 12.5
1 bmw 24.6
2 tata 10.6
After adding onroadprice column, Car Details:
name showroomprice onroadprice
0 benz 12.5 16.8
1 bmw 24.6 29.6
2 tata 10.6 14.8
name showroomprice
0 benz 12.5
1 bmw 24.6
2 tata 10.6
After adding onroadprice column, Car Details:
name showroomprice onroadprice
0 benz 12.5 16.8
1 bmw 24.6 29.6
2 tata 10.6 14.8