Вы находитесь на странице: 1из 5

# 1. Se dau doua liste.

Creati o a treia lista prin alegerea elementelor cu indexul


impar din prima lista si a celor cu index par din a doua lista.

listOne = [3, 6, 9, 12, 15, 18, 21]


listTwo = [4, 8, 12, 16, 20, 24, 28]

lp=listOne[1::2]
print(lp)

li=listTwo[0::2]
print(li)

list = [lp, li]


print(list)

SAU:

listOne = [3, 6, 9, 12, 15, 18, 21]


listTwo = [4, 8, 12, 16, 20, 24, 28]
listThree = list()
oddElements = listOne[1::2]
print("Element at odd-index positions from list one")
print(oddElements)
EvenElement = listTwo[0::2]
print("Element at odd-index positions from list two")
print(EvenElement)
print("Printing Final third list")
listThree.extend(oddElements)
listThree.extend(EvenElement)
print(listThree)

# Rezultat asteptat: [6, 12, 18, 4, 12, 20, 28]

# 2. Din fisierul Automobile listati primele si ultimile cinci randuri

import pandas as pd
df = pd.read_csv("Automobile_data.csv")
print(df.head(5))
print(df.tail(5))

# 3. Curatati datele si actualiza?i fisierul CSV Automobile - �nlocuii toate


valorile coloanelor care contin "?" si n.a cu NaN.

import pandas as pd
df = pd.read_csv('Automobile_data.csv')
df.replace(to_replace =["?", "n.a"],
value ="NaN")
print(df)

SAU:

import pandas as pd
df = pd.read_csv("Automobile_data.csv", na_values={
'price':["?","n.a"],
'stroke':["?","n.a"],
'horsepower':["?","n.a"],
'peak-rpm':["?","n.a"],
'average-mileage':["?","n.a"]})
print (df)
df.to_csv("Automobile_data.csv")

# 4. Pentru lista de mai jos eliminati elementul cu indexul patru si �l adaugati �n


pozitia a doua precum si la sf�rsitul listei

List = [34, 54, 67, 89, 11, 43, 94]


List.pop(4)
print(List)
List.insert(2, 11)
List.insert(7, 11)
print(List)

SAU:

sampleList = [34, 54, 67, 89, 11, 43, 94]


print("Origigal list ", sampleList)
element = sampleList.pop(4)
print("List After removing element at index 4 ", sampleList)
sampleList.insert(2, element)
print("List after Adding element at index 2 ", sampleList)
sampleList.append(element)
print("List after Adding element at last ", sampleList)

# 5. Din fi?ierul CSV Automobile gasiti numele companiei cu masinile cele mai
scumpe �
listati numele companiei care are cea mai scumpa masina si pretul acesteia

import pandas as pd
df = pd.read_csv("Automobile_data.csv")
df = df [['company','price']][df.price==df['price'].max()]
print(df)

# 6. Iterati lista de mai jos, numarati de c�te ori se �nt�lneste fiecare elemant
si
creati un dixtionar �n care sa aratati de c�te ori se �nt�lneste elemental

sampleList = [11, 45, 8, 11, 23, 45, 23, 45, 89]


print("Origigal list ", sampleList)
countDict = dict()
for item in sampleList:
if(item in countDict):
countDict[item] += 1
else:
countDict[item] = 1
print("Printing count of each item ",countDict)

# 7. Creati dictionarul de mai jos, luati toate elementele din el si adaugatile


�ntr-o lista, dar fara a adauga duplicate

speed ={'jan':47, 'feb':52, 'march':47, 'April':44, 'May':52, 'June':53,


'july':54, 'Aug':44, 'Sept':54}
print("Dictionary's values - ", speed.values())
speedList = list()
for item in speed.values():
if item not in speedList:
speedList.append(item)
print("unique list", speedList)

# 8. Din fi?ierul CSV Automobile listati detaliile tuturor masinilor Toyota Cars
import pandas as pd
df = pd.read_csv("Automobile_data.csv")
car_Manufacturers = df.groupby('company')
toyotaDf = car_Manufacturers.get_group('toyota')
print(toyotaDf)

# 9. Din fi?ierul CSV Automobile gasi?i kilometrajul mediu al fiecarei companii de


produc?ie de masini

import pandas as pd
df = pd.read_csv("Automobile_data.csv")
car_Manufacturers = df.groupby('company')
mileageDf = car_Manufacturers['company','average-mileage'].mean()
print(mileageDf)

# 10. Eliminati duplicatele dintr-o lista, creati un tuplu si gasiti numarul minim
si numarul maxim. De exemplu :
sampleList = [87, 45, 41, 65, 94, 41, 99, 94]

# eliminare duplicate
sampleList = list(dict.fromkeys(sampleList))
print(sampleList)

# creare tuplu
tuplu = tuple(sampleList)
print(tuplu)

# max si min
print(max(tuplu))
print(min(tuplu))

SAU:

sampleList = [87, 52, 44, 53, 54, 87, 52, 53]


print("Original list", sampleList)
sampleList = list(set(sampleList))
print("unique list", sampleList)
tuple = tuple(sampleList)
print("tuple ", tuple)
print("Minimum number is: ", min(tuple))
print("Maximum number is: ", max(tuple))

# 11. Din fi?ierul CSV Automobile afisati numarul total de masini pe fiecare
companie

import pandas as pd
pd.read_csv('Automobile_data.csv', delimiter = ',')
auto = pd.read_csv('Automobile_data.csv', delimiter = ',')
print(auto.groupby('company').count())

SAU:

import pandas as pd
df = pd.read_csv("Automobile_data.csv")
print(df['company'].value_counts())

# 12. Din fi?ierul CSV Automobile sortati toate masinile dupa coloana Price
# importing pandas package
import pandas as pd

# making data frame from csv file


df = pd.read_csv("Automobile_data.csv")

# sorting data frame by Price


df.sort_values(["price"], axis=0,
ascending=True, inplace=True)

# display
print(df)

SAU:

import pandas as pd
carsDf = pd.read_csv("Automobile_data.csv")
carsDf = carsDf.sort_values(by=['price', 'horsepower'], ascending=False)
print(carsDf)

# 13. Din fi?ierul CSV Automobile gasiti pentru fiecare companie masina cu cel mai
mare pret

import pandas as pd
pd.read_csv('Automobile_data.csv', delimiter = ',')
auto = pd.read_csv('Automobile_data.csv', delimiter = ',')
print(auto.groupby('company').max())

SAU:

import pandas as pd
df = pd.read_csv("Automobile_data.csv")
car_Manufacturers = df.groupby('company')
priceDf = car_Manufacturers['company','price'].max()
print(priceDf)

# 14. Create two data frames using following two Dicts, Merge two data frames, and
append second data frame as a new column to first data frame.
Car_Price = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'Price': [23845, 17995,
135925 , 71400]}
car_Horsepower = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'horsepower':
[141, 80, 182 , 160]}

# creare df
import pandas as pd
df1 = pd.DataFrame(Car_Price, columns = ['Company', 'Price'])
print(df1)
df2 = pd.DataFrame(car_Horsepower, columns=['Company', 'horsepower'])
print(df2)

# merge df and append


print(pd.merge(df1, df2, on='Company'))

SAU:

import pandas as pd
Car_Price = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'Price': [23845, 17995,
135925 , 71400]}
carPriceDf = pd.DataFrame.from_dict(Car_Price)
car_Horsepower = {'Company': ['Toyota', 'Honda', 'BMV', 'Audi'], 'horsepower':
[141, 80, 182 , 160]}
carsHorsepowerDf = pd.DataFrame.from_dict(car_Horsepower)
carsDf = pd.merge(carPriceDf, carsHorsepowerDf, on="Company")
print(carsDf)

# 15. Cititi fisierul company_sales_data.csv si reprezentati profitul total pentru


toate lunile utiliz�nd line plot
# Total profit data provided for each month. Generated line plot must include the
following properties: �
# � X label name = Month Number
# � Y label name = Total profit
# The line plot graph should look like this.

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("company_sales_data.csv")
profitList = df ['total_profit'].tolist()
monthList = df ['month_number'].tolist()
plt.plot(monthList, profitList, label = 'Month-wise Profit data of last year')
plt.xlabel('Month number')
plt.ylabel('Profit in dollar')
plt.xticks(monthList)
plt.title('Company profit per month')
plt.yticks([100000, 200000, 300000, 400000, 500000])
plt.show()

# 16. Calculate total sale data for last year for each product and show it using a
Pie chart (company_sales_data.csv file)
# Note: In Pie chart display Number of units sold per year for each product in
percentage. The Pie chart should look like this.

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("company_sales_data.csv")
monthList = df ['month_number'].tolist()
labels = ['FaceCream', 'FaseWash', 'ToothPaste', 'Bathing soap', 'Shampoo',
'Moisturizer']
salesData = [df ['facecream'].sum(), df ['facewash'].sum(), df
['toothpaste'].sum(),
df ['bathingsoap'].sum(), df ['shampoo'].sum(), df ['moisturizer'].sum()]
plt.axis("equal")
plt.pie(salesData, labels=labels, autopct='%1.1f%%')
plt.legend(loc='lower right')
plt.title('Sales data')
plt.show()

https://pynative.com/python-exercises-with-solutions/

Вам также может понравиться