Pandas םע הלועפל תונתינ תונבותל ן"לדנ ינותנ תכיפה :SQL-ל רבעמ
.םינותנ ןיבהלו חתנל ידכ Python-ב SQL תויומד תויצקנופ ליחת ,ךשמהב .SQL לש יתרוס
.ליחתנ ואוב
תיללכ הריקס
:םה ;םיקלח השולשל קלוחמ הז טסופ
- Pandas לש
DataFrame.query()
תטיש םע םינותנ רקח - םינותנ ץוביקו הריבצ
- תודנפב תודומעו תורוש תריחבב הטילש
- קימעמ רויד קוש חותינל ריצ תלבט תמיתר
Pandas לש DataFrame.query()
תטיש םע םינותנ רקח
.רתוי םיבכרומ םינותנ תתליאשל סיסבה תא חינמ ךכבו ,םיבורמו םידדוב םיאנת ךמס לע ם
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# Load the dataset
Ames = pd.read_csv('Ames.csv')
# Simple querying: Select houses priced above $600,000
high_value_houses = Ames.query('SalePrice > 600000')
print(high_value_houses)
.'SalePrice > 600000'
,הז הרקמב .תזורחמכ ןיוצש יאנת לע ססבתהב םינ
.רתויב הובגה ךרעה ילעב םיסכנה לש םימוקימהו םינייפאמה יבגל תונבות העיצמו ,סמייא
PID GrLivArea ... Latitude Longitude
65 528164060 2470 ... 42.058475 -93.656810
584 528150070 2364 ... 42.060462 -93.655516
1007 528351010 4316 ... 42.051982 -93.657450
1325 528320060 3627 ... 42.053228 -93.657649
1639 528110020 2674 ... 42.063049 -93.655918
[5 rows x 85 columns]
.תינמז וב םינותנה ךרעמ לע םיבורמ םיננסמ ליחהל ךל רשפאמה ,(&
) יגול
# Advanced querying: Select houses with more than 3 bedrooms and priced below $300,000
specific_houses = Ames.query('BedroomAbvGr > 3 & SalePrice < 300000')
print(specific_houses)
.םיוסמ ביצקת חווט ךותב תוחוורמ םירוגמ תויורשפא תושפחמה תוחפשמ ןיינעל לוכיש רוי
PID GrLivArea ... Latitude Longitude
5 908128060 1922 ... 42.018988 -93.671572
23 902326030 2640 ... 42.029358 -93.612289
33 903400180 1848 ... 42.029544 -93.627377
38 527327050 2030 ... 42.054506 -93.631560
40 528326110 2172 ... 42.055785 -93.651102
... ... ... ... ... ...
2539 905101310 1768 ... 42.033393 -93.671295
2557 905107250 1440 ... 42.031349 -93.673578
2562 535101110 1584 ... 42.048256 -93.619860
2575 905402060 1733 ... 42.027669 -93.666138
2576 909275030 2002 ... NaN NaN
[352 rows x 85 columns]
.וניוצש םינוירטירקה תרגסמב הלא םיתב לש הכישמהו תולעה תולע לע םיעיפשמ הנישה ירד
# Visualizing the advanced query results
plt.figure(figsize=(10, 6))
sns.scatterplot(x='GrLivArea', y='SalePrice', hue='BedroomAbvGr', data=specific_houses, palette='viridis')
plt.title('Sales Price vs. Ground Living Area')
plt.xlabel('Ground Living Area (sqft)')
plt.ylabel('Sales Price ($)')
plt.legend(title='Bedrooms Above Ground')
plt.show()
.הדובע דוק םע ימצע דומילל תוכרדה קפסמ אוה .T
םינותנ ץוביקו הריבצ
.הוויא ,סמייא לש יבחרמה סבנקה ינפ לע יאלמבו רוידל תוריבס תולעב תונושה תא שיגדה
# Advanced querying: Select houses with more than 3 bedrooms and priced below $300,000
specific_houses = Ames.query('BedroomAbvGr > 3 & SalePrice < 300000')
# Group by neighborhood, then calculate the average and total sale price, and count the houses
grouped_data = specific_houses.groupby('Neighborhood').agg({
'SalePrice': ['mean', 'count']
})
# Renaming the columns for clarity
grouped_data.columns = ['Average Sales Price', 'House Count']
# Round the average sale price to 2 decimal places
grouped_data['Averages Sales Price'] = grouped_data['Average Sales Price'].round(2)
print(grouped_data)
Average Sales Price House Count
Neighborhood
BrDale 113700.00 1
BrkSide 154840.00 10
ClearCr 206756.31 13
CollgCr 233504.17 12
Crawfor 199946.68 19
Edwards 142372.41 29
Gilbert 222554.74 19
IDOTRR 146953.85 13
MeadowV 135966.67 3
Mitchel 152030.77 13
NAmes 158835.59 59
NPkVill 143000.00 1
NWAmes 203846.28 39
NoRidge 272222.22 18
NridgHt 275000.00 3
OldTown 142586.72 43
SWISU 147493.33 15
Sawyer 148375.00 16
SawyerW 217952.06 16
Somerst 247333.33 3
StoneBr 270000.00 1
Timber 247652.17 6
.שבוגמו דחא ףרגב חפנב ןהו ריחמה תא ןה שיחמהל ידכ םיתב תוריפס לש תורעה תפסותב ,
# Ensure 'Neighborhood' is a column (reset index if it was the index)
grouped_data_reset = grouped_data.reset_index().sort_values(by='Average Sales Price')
# Set the aesthetic style of the plots
sns.set_theme(style="whitegrid")
# Create the bar plot
plt.figure(figsize=(12, 8))
barplot = sns.barplot(
x='Neighborhood',
y='Average Sales Price',
data=grouped_data_reset,
palette="coolwarm",
hue='Neighborhood',
legend=False,
errorbar=None # Removes the confidence interval bars
)
# Rotate the x-axis labels for better readability
plt.xticks(rotation=45)
# Annotate each bar with the house count, using enumerate to access the index for positioning
for index, value in enumerate(grouped_data_reset['Average Sales Price']):
house_count = grouped_data_reset.loc[index, 'House Count']
plt.text(index, value, f'{house_count}', ha='center', va='bottom')
plt.title('Average Sales Price by Neighborhood', fontsize=18)
plt.xlabel('Neighborhood')
plt.ylabel('Average Sales Price ($)')
plt.tight_layout() # Adjust the layout
plt.show()
.םיימוקמה ן"לדנה יקווש לש הקימנידה יבגל תובושח תונבות קפסמ םג אלא ,יתימאה םלוע
תודנפב תודומעו תורוש תריחבב הטילש
.תודומעלו תורושל םיסחייתמ םה ובש ןפואב םינוש םה ךא - םינותנ רוחבל - תומוד תורט
DataFrame.loc[]
תטיש תנבה
DataFrame.loc[]
is a label-based data selection method, meaning you use the labels of rows and columns to select the data. It’s highly intuitive for selecting data based on column names and row indexes when you know the specific labels you’re interested in.Syntax:
DataFrame.loc[row_label, column_label]
דעי: הנוכש' תא גיצנו ,(ךלש םימדוקה םיאצממה לע ססבתהב) םהלש ם
# Assuming 'high_value_neighborhoods' is a list of neighborhoods with higher average sale prices
high_value_neighborhoods = ['NridgHt', 'NoRidge', 'StoneBr']
# Use df.loc[] to select houses based on your conditions and only in high-value neighborhoods
high_value_houses_specific = Ames.loc[(Ames['BedroomAbvGr'] > 3) &
(Ames['SalePrice'] < 300000) &
(Ames['Neighborhood'].isin(high_value_neighborhoods)),
['Neighborhood', 'SalePrice', 'GrLivArea']]
print(high_value_houses_specific.head())
Neighborhood SalePrice GrLivArea
40 NoRidge 291000 2172
162 NoRidge 285000 2225
460 NridgHt 250000 2088
468 NoRidge 268000 2295
490 NoRidge 260000 2417
DataFrame.iloc[]
תטיש תנבה
.DataFrame-ב םמוקימ יפל םינותנל תשגל דחוימב ישומיש הז .רוחבל ךנוצרבש תודומעהו
ריבחת: DataFrame.iloc[row_position, column_position]
הרטמ: הובג ךרע תולעב תונוכשל ץוחמ $300,000-ל תחתמ םריחמו הגרד
# Filter for houses not in the 'high_value_neighborhoods',
# with at least 3 bedrooms above grade, and priced below $300,000
low_value_spacious_houses = Ames.loc[(~Ames['Neighborhood'].isin(high_value_neighborhoods)) &
(Ames['BedroomAbvGr'] >= 3) &
(Ames['SalePrice'] < 300000)]
# Sort these houses by 'SalePrice' to highlight the lower end explicitly
low_value_spacious_houses_sorted = low_value_spacious_houses.sort_values(by='SalePrice').reset_index(drop=True)
# Using df.iloc to select and print the first 5 observations of such low-value houses
low_value_spacious_first_5 = low_value_spacious_houses_sorted.iloc[:5, :]
# Print only relevant columns to match the earlier high-value example: 'Neighborhood', 'SalePrice', 'GrLivArea'
print(low_value_spacious_first_5[['Neighborhood', 'SalePrice', 'GrLivArea']])
Neighborhood SalePrice GrLivArea
0 IDOTRR 40000 1317
1 IDOTRR 50000 1484
2 IDOTRR 55000 1092
3 Sawyer 62383 864
4 Edwards 63000 1112
.רתוי הנבותו דקוממ םינותנ רקח תרשפאמו ,ךלש םינותנה יעדמל םילכה תכרע תא הרישעמ
קימעמ רויד קוש חותינל ריצ תואלבט לוצינ
.הריכמה יריחמו הנישה ירדח רפסמ ,הנוכשה ינייפאמ ןיב ןילמוגה קחשמב תודקמתה ךות ,
.סמייא ךותב רוידה תפדעהו רוידה תוריבס תא םיביתכמש םיסופד ףושחל הרטמב ,הניש ירד
# Import an additional library
import numpy as np
# Filter for houses priced below $300,000 and with at least 1 bedroom above grade
affordable_houses = Ames.query('SalePrice < 300000 & BedroomAbvGr > 0')
# Create a pivot table to analyze average sale price by neighborhood and number of bedrooms
pivot_table = affordable_houses.pivot_table(values='SalePrice',
index='Neighborhood',
columns='BedroomAbvGr',
aggfunc='mean').round(2)
# Fill missing values with 0 for better readability and to indicate no data for that segment
pivot_table = pivot_table.fillna(0)
# Adjust pandas display options to ensure all columns are shown
pd.set_option('display.max_columns', None)
print(pivot_table)
.תונבות המכב ןודנש ינפל ריצה תלבט לע ריהמ טבמ חקינ ואוב
BedroomAbvGr 1 2 3 4 5 6
Neighborhood
Blmngtn 178450.00 197931.19 0.00 0.00 0.00 0.00
Blueste 192500.00 128557.14 151000.00 0.00 0.00 0.00
BrDale 0.00 99700.00 111946.43 113700.00 0.00 0.00
BrkSide 77583.33 108007.89 140058.67 148211.11 214500.00 0.00
ClearCr 212250.00 220237.50 190136.36 209883.20 196333.33 0.00
CollgCr 154890.00 181650.00 196650.98 233504.17 0.00 0.00
Crawfor 289000.00 166345.00 193433.75 198763.94 210000.00 0.00
Edwards 59500.00 117286.27 134660.65 137332.00 191866.67 119900.00
Gilbert 0.00 172000.00 182178.30 223585.56 204000.00 0.00
Greens 193531.25 0.00 0.00 0.00 0.00 0.00
GrnHill 0.00 230000.00 0.00 0.00 0.00 0.00
IDOTRR 67378.00 93503.57 111681.13 144081.82 162750.00 0.00
Landmrk 0.00 0.00 137000.00 0.00 0.00 0.00
MeadowV 82128.57 105500.00 94382.00 128250.00 151400.00 0.00
Mitchel 176750.00 150366.67 168759.09 149581.82 165500.00 0.00
NAmes 139500.00 133098.93 146260.96 159065.22 180360.00 144062.50
NPkVill 0.00 134555.00 146163.64 143000.00 0.00 0.00
NWAmes 0.00 177765.00 183317.12 201165.00 253450.00 0.00
NoRidge 0.00 262000.00 259436.67 272222.22 0.00 0.00
NridgHt 211700.00 215458.55 264852.71 275000.00 0.00 0.00
OldTown 83333.33 105564.32 136843.57 136350.91 167050.00 97500.00
SWISU 60000.00 121044.44 132257.88 143444.44 158500.00 148633.33
Sawyer 185000.00 124694.23 138583.77 148884.62 0.00 146166.67
SawyerW 216000.00 156147.41 185192.14 211315.00 0.00 237863.25
Somerst 205216.67 191070.18 225570.39 247333.33 0.00 0.00
StoneBr 223966.67 211468.75 233750.00 270000.00 0.00 0.00
Timber 0.00 217263.64 200536.04 241202.60 279900.00 0.00
Veenker 247566.67 245150.00 214090.91 0.00 0.00 0.00
:תויזכרמ תונבות רפסמ ףשוח הז חותינ .הניש ירדח לש תונוש תוריפס תללכה םע תונוכש
- הנוכש יפל ריבס ריחמ: תיבב םידקוממ םישופיחב עייסמש המ ,תיפיצפס
- ריחמה לע הנישה ירדח תעפשה: רתוי םילודג םיתב לע תחנומה הימרפה
- תויונמדזהו קוש ירעפ: םיעיקשמו םיחתפמ רובע תויונמדזה וא םיילאי
.יתוזח חותינ םע בולישב לצנתמ ןהלש יתימאה לאיצנטופה ,תונבות ריצ תואלבט ןהש המכ
.הניש ירדחו תונוכש תוריפס לש םימייק אל םיבוליש קהבומ ןפואב השיגדמה תישיא תמאתו
# Import an additional library
import matplotlib.colors
# Create a custom color map
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", ["red", "yellow", "green"])
# Mask for "zero" values to be colored with a different shade
mask = pivot_table == 0
# Set the size of the plot
plt.figure(figsize=(14, 10))
# Create a heatmap with the mask
sns.heatmap(pivot_table,
cmap=cmap,
annot=True,
fmt=".0f",
linewidths=.5,
mask=mask,
cbar_kws={'label': 'Average Sales Price ($)'})
# Adding title and labels for clarity
plt.title('Average Sales Price by Neighborhood and Number of Bedrooms', fontsize=16)
plt.xlabel('Number of Bedrooms Above Grade', fontsize=12)
plt.ylabel('Neighborhood', fontsize=12)
# Display the heatmap
plt.show()
.תוריבס ריחמ תודוקנב ההובג הניש ירדח תריפס םע םיסכנ םישפחמה םיעיקשמ וא רתוי תו
.רוידה םוחת לע תויביטמרופניא תונבות ףושחל תולוכי םינותנ לש הימדהו היצלופינמ לש
תפסונ האירק
.קימעהל הצור התא םא אשונב םיפסונ םיבאשמ קפסמ הז ףיעס
ןותייפ דועית
- Pandas לש
DataFrame.query()
תטיש - Pandas לש
DataFrame.groupby()
תטיש - Pandas לש
DataFrame.loc[]
תטיש - Pandas לש
DataFrame.iloc[]
תטיש - Pandas לש
DataFrame.pivot_table()
תטיש
םיבאשמ
- סמייא לש םינותנ תכרע
- ןולימ םינותנ סמייא
םוכיס
:דציכ תדמל ,יפיצפס ןפואב .קימעמ םינותנ רקחל םישורדה םילכב םיטסילנאה תא תודייצמ
- .SQL לש
SELECT
תרהצהל המודב םינותנ תריחבלDataFrame.query()
- .SQL לש
GROUP BY
-ל המודב ,םינותנ םוכיסו הריבצלDataFrame.gr
- .רתוי קימעמ חותינל
DataFrame.pivot_table()
-וDataFrame.loc[
.תונעל יתלוכי בטימכ השעא ינאו ,הטמל תובוגתב ךיתולאש תא לאש אנא ?ןהשלכ תולאש ךל