How does numpy store an image array? - python

I imported a picture as NumPy array, and I thought the data structure should like [[255, 255, 255][255,255,255]...[255, 255, 255] because of the RGB colour. However, the real structure is:
[[225 225 225 ... 233 232 233]
[225 225 225 ... 233 233 233]
[226 226 225 ... 233 232 233]
...
[225 226 225 ... 233 233 233]
[226 226 225 ... 233 232 233]
[226 226 226 ... 232 233 234]]
[[225 225 225 ... 233 232 233]
[225 225 225 ... 233 233 233]
[226 226 225 ... 233 232 233]
...
[225 226 225 ... 233 233 233]
[226 226 225 ... 233 232 233]
[226 226 226 ... 232 233 234]]
And when I print it one by one, just like the previous code is Img and this is Img[0], strange things happen.
[225 225 225 226 226 226 225 226 226 225 255 226 226 226 222 228 255 228
226 226 226 226 226 226 226 226 228 226 228 226 226 228 228 226 226 228
226 226 255 228 226 226 226 226 228 228 228 255 255 228 228 228 228 228
228 229 228 228 228 228 228 222 228 228 228 228 226 228 228 228 228 226
255 228 0 226 228 228 228 228 228 228 228 228 226 228 228 228 228 0
226 226 228 228 255 226 228 228 0 228 228 228 228 228 228 255 228 228
228 228 228 228 228 226 225 224 226 226 228 228 228 226 225 228 228 228
228 228 228 228 226 228 228 228 228 228 228 228 228 228 228 228 228 228
228 228 228 228 228 228 228 229 228 228 228 229 228 0 228 228 228 229
228 228 229 229 229 229 255 229 229 229 229 229 229 229 228 228 228 228
229 229 229 229 228 229 229 229 229 229 230 229 229 229 229 0 229 229
229 229 230 229 229 231 0 231 229 230 230 231 229 231 230 231 231 230
230 230 231 230 232 232 232 230 232 231 230 231 230 232 229 231 231 232
232 230 232 232 231 231 232 231 232 233 232 233 232 232 231 232 233 233
232 233 232 231 232 231 233 255 233 233 232 233 233 233 232 232 0 233
233 233 233 233 233 232 231 233 232 233 233 231 233 233 233 233 231 233
233 233 233 232 233 233 232 233 255 233 234 233 232 232 234 231 234 233
233 233]
What's the meaning of the numbers and what's the real structure of the NumPy image array?
Thanks!

This is a grayscale image, that is why you have a 2D array. If it was a color image, it would have three channels, hence, a 3D array.

Related

ValueError: Invalid classes inferred from unique values of `y` in XGBoost

I'm new to the Data Science field and I'm trying to apply XGBoost in a table having 5 rows × 46 columns
and my last column is my target column.
import sys
!{sys.executable} -m pip install xgboost
import xgboost as xgb
from sklearn.model_selection import train_test_split
x=df_null_mean.iloc[:,:-1]
y=df_null_mean.iloc[:,-1]
x_cols=x.columns
# Splitting the dataset into the Training set and Test set
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)
# Fitting XGBoost to the training data
my_model = xgb.XGBClassifier()
my_model.fit(x_train, y_train)
and the error I'm getting is
ValueError: Invalid classes inferred from unique values of `y`. Expected: [ 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], got [ 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 544 545 546 547 548 549 550 551 553 554 555 556 557 558 559
560 562 563 564 565 567 568 569 570 572 573 574 576 577 578 579 580 581
582 583 584 585 586 587 588 589 590 591 592 593 595 596 598 599 602 605
606 607 608 609 614 615 617 619 622 626 628 629 630 631 632 638 639 640
642 647 650 659 665 673 674 680 684 685 688 691 703 710 713 714 715 716
717 718 719 727 730 731 763 786 812 850 854 857 862 870 876 878 880 884
889 892 894 898 900 902]
Can anyone help me with the resolution?
import sys
!{sys.executable} -m pip install xgboost
import xgboost as xgb
from sklearn.model_selection import train_test_split
x=df_null_mean.iloc[:,:-1]
y=df_null_mean.iloc[:,-1]
x_cols=x.columns
# Splitting the dataset into the Training set and Test set
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=0)
# Fitting XGBoost to the training data
my_model = xgb.XGBClassifier()
my_model.fit(x_train, y_train)
I think you need to have the class numerotated from 0 to n-1 where n is your number of class.
Try this:
from sklearn.preprocessing import LabelEncoder
le = LabelEncoder()
y_train = le.fit_transform(y_train)

How to groupby a date range and a column then plot a bar plot

Let's say, I have this specific dataframe below.
import pandas as pd
import numpy as np
periods = 46670
dates = pd.date_range(start='2005-07-01', end='2021-06-01', periods=periods)
operating_airline = ['Lufthansa','Air Canada','American Air','American Pan Pacific','Emirates','KLM','Scandinavian Air',
'Singapore Airlines','Japan Air','Air Force 1']
geo_summary = ['Domestic', 'International']
geo_region = ['US','Canada','South America', 'Europe','Nothern Europe']
np.random.seed(2002) # for repeatable values
operating_airline = np.random.choice(operating_airline, size=periods)
geo_summary = np.random.choice(geo_summary, size=periods)
geo_region = np.random.choice(geo_region, size=periods)
passenger_count = np.random.randint(1000,10000, size=periods)
test = pd.DataFrame({'Dates':dates,'Operating_Airlines':operating_airline,'Geo_Summary':geo_summary,'Geo_Region':geo_region,'Passenger_Count':passenger_count})
# display(test.head())
Dates Operating_Airlines Geo_Summary Geo_Region Passenger_Count
0 2005-07-01 00:00:00.000000000 Air Canada Domestic South America 9958
1 2005-07-01 02:59:23.667530909 American Air Domestic Europe 7853
2 2005-07-01 05:58:47.335061818 Japan Air International Canada 3162
3 2005-07-01 08:58:11.002592727 Air Force 1 International South America 5100
4 2005-07-01 11:57:34.670123636 Japan Air International Canada 5382
What i've been trying to achieve mostly;
Note: The bars should have annotations(although im aware of how to do this part, id still like see a different approach. if there is).
My issue was that Im unable to customise Dates format(e.g. y-m-d) & date range(6month, a year) simultaneously plotting 2 variables Air Canada and American Pan Pacific in the Operating_Airline using only Pandas &/or Matplotlib. Im open to all types of answers ofcourse!
How could I customize date ranges further if I decided to plot for a yearly period?
What I've tried(failed & unable to find a solution) to;
plt.bar(test['Date'], test['Operating_Airline'].count(), label='Test', width=20, color=['red'])
plt.bar(test['Date'], test['Operating_Airline'].count(), label='Test_1', width=20)
plt.title('Test')
plt.legend()
Use pandas.Grouper with pandas.DataFrame.groupby to group 'Dates' by a frequency (e.g. '6M', '1Y')
This results in a long dataframe, which can be plotted with seaborn.catplot or seaborn.barplot.
The dates can be reformatted with pandas.Series.dt.strftime, after using Grouper, because Grouper requires the dates to be a datetime Dtype, but .dt.strftime converts the dates to strings.
Use pandas.DataFrame.pivot to reshape the dataframe to a wide form, and plot with pandas.DataFrame.plot.
From matplotlib 3.4.0, matplotlib.pyplot.bar_label can be used to easily annotate bars.
See this answer for additional details and examples using .bar_label.
Since there are many dates, it's better to plot horizontal bars, than vertical bars (for spacing). For vertical bars with pandas, use 'bar' instead of 'barh', and for seaborn, swap the columns passed to x= and y=.
Tested in python 3.10, pandas 1.4.3, matplotlib 3.5.1, seaborn 0.11.2
# use groupby grouper and specify freq='1Y' or '6M'
dfg = test.groupby([pd.Grouper(key="Dates", freq="1Y"), 'Operating_Airlines']).Operating_Airlines.count().reset_index(name='counts')
# now change the format of the dates
dfg.Dates = dfg.Dates.dt.strftime('%Y-%m')
# pivot dfg so it can be plotted directly with pandas
dfp = dfg.pivot(index='Dates', columns='Operating_Airlines', values='counts')
# plot dfp
ax = dfp.plot(kind='barh', width=0.90, figsize=(10, 22))
# move the legend
ax.legend(title='Operating_Airlines', bbox_to_anchor=(1, 0.5), loc='center left', frameon=False)
# annotate the bars
for c in ax.containers:
ax.bar_label(c, label_type='edge', fontsize=8)
Instead of plotting dfp (wide form) with pandas, plot dfg (long form) directly with seaborn.
import seaborn as sns
# plot dfg
g = sns.catplot(kind='bar', data=dfg, y='Dates', x='counts', hue='Operating_Airlines', height=20, aspect=0.5)
for c in g.ax.containers:
g.ax.bar_label(c, label_type='edge', fontsize=8)
DataFrame Views
dfg
Dates Operating_Airlines counts
0 2005-12 Air Canada 139
1 2005-12 Air Force 1 147
2 2005-12 American Air 138
3 2005-12 American Pan Pacific 148
4 2005-12 Emirates 159
5 2005-12 Japan Air 136
6 2005-12 KLM 137
7 2005-12 Lufthansa 151
8 2005-12 Scandinavian Air 166
9 2005-12 Singapore Airlines 156
10 2006-12 Air Canada 277
11 2006-12 Air Force 1 297
12 2006-12 American Air 299
13 2006-12 American Pan Pacific 286
14 2006-12 Emirates 312
15 2006-12 Japan Air 297
16 2006-12 KLM 312
17 2006-12 Lufthansa 290
18 2006-12 Scandinavian Air 270
19 2006-12 Singapore Airlines 290
20 2007-12 Air Canada 301
21 2007-12 Air Force 1 268
22 2007-12 American Air 267
23 2007-12 American Pan Pacific 297
24 2007-12 Emirates 298
25 2007-12 Japan Air 291
26 2007-12 KLM 295
27 2007-12 Lufthansa 290
28 2007-12 Scandinavian Air 316
29 2007-12 Singapore Airlines 307
30 2008-12 Air Canada 296
31 2008-12 Air Force 1 279
32 2008-12 American Air 286
33 2008-12 American Pan Pacific 316
34 2008-12 Emirates 306
35 2008-12 Japan Air 290
36 2008-12 KLM 286
37 2008-12 Lufthansa 284
38 2008-12 Scandinavian Air 281
39 2008-12 Singapore Airlines 314
40 2009-12 Air Canada 312
41 2009-12 Air Force 1 264
42 2009-12 American Air 329
43 2009-12 American Pan Pacific 276
44 2009-12 Emirates 284
45 2009-12 Japan Air 273
46 2009-12 KLM 313
47 2009-12 Lufthansa 304
48 2009-12 Scandinavian Air 292
49 2009-12 Singapore Airlines 283
50 2010-12 Air Canada 300
51 2010-12 Air Force 1 279
52 2010-12 American Air 291
53 2010-12 American Pan Pacific 292
54 2010-12 Emirates 284
55 2010-12 Japan Air 309
56 2010-12 KLM 303
57 2010-12 Lufthansa 283
58 2010-12 Scandinavian Air 309
59 2010-12 Singapore Airlines 280
60 2011-12 Air Canada 293
61 2011-12 Air Force 1 304
62 2011-12 American Air 279
63 2011-12 American Pan Pacific 330
64 2011-12 Emirates 279
65 2011-12 Japan Air 287
66 2011-12 KLM 286
67 2011-12 Lufthansa 281
68 2011-12 Scandinavian Air 299
69 2011-12 Singapore Airlines 292
70 2012-12 Air Canada 312
71 2012-12 Air Force 1 291
72 2012-12 American Air 276
73 2012-12 American Pan Pacific 312
74 2012-12 Emirates 303
75 2012-12 Japan Air 304
76 2012-12 KLM 271
77 2012-12 Lufthansa 282
78 2012-12 Scandinavian Air 301
79 2012-12 Singapore Airlines 286
80 2013-12 Air Canada 274
81 2013-12 Air Force 1 301
82 2013-12 American Air 298
83 2013-12 American Pan Pacific 283
84 2013-12 Emirates 347
85 2013-12 Japan Air 303
86 2013-12 KLM 270
87 2013-12 Lufthansa 290
88 2013-12 Scandinavian Air 279
89 2013-12 Singapore Airlines 284
90 2014-12 Air Canada 288
91 2014-12 Air Force 1 317
92 2014-12 American Air 312
93 2014-12 American Pan Pacific 296
94 2014-12 Emirates 309
95 2014-12 Japan Air 275
96 2014-12 KLM 273
97 2014-12 Lufthansa 278
98 2014-12 Scandinavian Air 296
99 2014-12 Singapore Airlines 286
100 2015-12 Air Canada 257
101 2015-12 Air Force 1 291
102 2015-12 American Air 305
103 2015-12 American Pan Pacific 279
104 2015-12 Emirates 331
105 2015-12 Japan Air 285
106 2015-12 KLM 320
107 2015-12 Lufthansa 306
108 2015-12 Scandinavian Air 280
109 2015-12 Singapore Airlines 276
110 2016-12 Air Canada 274
111 2016-12 Air Force 1 292
112 2016-12 American Air 272
113 2016-12 American Pan Pacific 322
114 2016-12 Emirates 309
115 2016-12 Japan Air 281
116 2016-12 KLM 263
117 2016-12 Lufthansa 305
118 2016-12 Scandinavian Air 328
119 2016-12 Singapore Airlines 292
120 2017-12 Air Canada 291
121 2017-12 Air Force 1 263
122 2017-12 American Air 298
123 2017-12 American Pan Pacific 312
124 2017-12 Emirates 280
125 2017-12 Japan Air 309
126 2017-12 KLM 312
127 2017-12 Lufthansa 293
128 2017-12 Scandinavian Air 298
129 2017-12 Singapore Airlines 274
130 2018-12 Air Canada 292
131 2018-12 Air Force 1 261
132 2018-12 American Air 318
133 2018-12 American Pan Pacific 297
134 2018-12 Emirates 312
135 2018-12 Japan Air 297
136 2018-12 KLM 264
137 2018-12 Lufthansa 286
138 2018-12 Scandinavian Air 300
139 2018-12 Singapore Airlines 303
140 2019-12 Air Canada 272
141 2019-12 Air Force 1 306
142 2019-12 American Air 288
143 2019-12 American Pan Pacific 287
144 2019-12 Emirates 281
145 2019-12 Japan Air 310
146 2019-12 KLM 288
147 2019-12 Lufthansa 296
148 2019-12 Scandinavian Air 335
149 2019-12 Singapore Airlines 267
150 2020-12 Air Canada 295
151 2020-12 Air Force 1 306
152 2020-12 American Air 267
153 2020-12 American Pan Pacific 305
154 2020-12 Emirates 294
155 2020-12 Japan Air 251
156 2020-12 KLM 326
157 2020-12 Lufthansa 336
158 2020-12 Scandinavian Air 282
159 2020-12 Singapore Airlines 275
160 2021-12 Air Canada 124
161 2021-12 Air Force 1 132
162 2021-12 American Air 118
163 2021-12 American Pan Pacific 115
164 2021-12 Emirates 134
165 2021-12 Japan Air 110
166 2021-12 KLM 115
167 2021-12 Lufthansa 125
168 2021-12 Scandinavian Air 130
169 2021-12 Singapore Airlines 110
dfp
Operating_Airlines Air Canada Air Force 1 American Air American Pan Pacific Emirates Japan Air KLM Lufthansa Scandinavian Air Singapore Airlines
Dates
2005-12 139 147 138 148 159 136 137 151 166 156
2006-12 277 297 299 286 312 297 312 290 270 290
2007-12 301 268 267 297 298 291 295 290 316 307
2008-12 296 279 286 316 306 290 286 284 281 314
2009-12 312 264 329 276 284 273 313 304 292 283
2010-12 300 279 291 292 284 309 303 283 309 280
2011-12 293 304 279 330 279 287 286 281 299 292
2012-12 312 291 276 312 303 304 271 282 301 286
2013-12 274 301 298 283 347 303 270 290 279 284
2014-12 288 317 312 296 309 275 273 278 296 286
2015-12 257 291 305 279 331 285 320 306 280 276
2016-12 274 292 272 322 309 281 263 305 328 292
2017-12 291 263 298 312 280 309 312 293 298 274
2018-12 292 261 318 297 312 297 264 286 300 303
2019-12 272 306 288 287 281 310 288 296 335 267
2020-12 295 306 267 305 294 251 326 336 282 275
2021-12 124 132 118 115 134 110 115 125 130 110

Seaborn Lineplot Confidence Interval not visible for all values [duplicate]

I am using sns.lineplot to show the confidence intervals in a plot.
sns.lineplot(x = threshold, y = mrl_array, err_style = 'band', ci=95)
plt.show()
I'm getting the following plot, which doesn't show the confidence interval:
What's the problem?
There is probably only a single observation per x value.
If there is only one observation per x value, then there is no confidence interval to plot.
Bootstrapping is performed per x value, but there needs to be more than one obsevation for this to take effect.
ci: Size of the confidence interval to draw when aggregating with an estimator. 'sd' means to draw the standard deviation of the data. Setting to None will skip bootstrapping.
Note the following examples from seaborn.lineplot.
This is also the case for sns.relplot with kind='line'.
The question specifies sns.lineplot, but this answer applies to any seaborn plot that displays a confidence interval, such as seaborn.barplot.
Data
import seaborn as sns
# load data
flights = sns.load_dataset("flights")
year month passengers
0 1949 Jan 112
1 1949 Feb 118
2 1949 Mar 132
3 1949 Apr 129
4 1949 May 121
# only May flights
may_flights = flights.query("month == 'May'")
year month passengers
4 1949 May 121
16 1950 May 125
28 1951 May 172
40 1952 May 183
52 1953 May 229
64 1954 May 234
76 1955 May 270
88 1956 May 318
100 1957 May 355
112 1958 May 363
124 1959 May 420
136 1960 May 472
# standard deviation for each year of May data
may_flights.set_index('year')[['passengers']].std(axis=1)
year
1949 NaN
1950 NaN
1951 NaN
1952 NaN
1953 NaN
1954 NaN
1955 NaN
1956 NaN
1957 NaN
1958 NaN
1959 NaN
1960 NaN
dtype: float64
# flight in wide format
flights_wide = flights.pivot("year", "month", "passengers")
month Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec
year
1949 112 118 132 129 121 135 148 148 136 119 104 118
1950 115 126 141 135 125 149 170 170 158 133 114 140
1951 145 150 178 163 172 178 199 199 184 162 146 166
1952 171 180 193 181 183 218 230 242 209 191 172 194
1953 196 196 236 235 229 243 264 272 237 211 180 201
1954 204 188 235 227 234 264 302 293 259 229 203 229
1955 242 233 267 269 270 315 364 347 312 274 237 278
1956 284 277 317 313 318 374 413 405 355 306 271 306
1957 315 301 356 348 355 422 465 467 404 347 305 336
1958 340 318 362 348 363 435 491 505 404 359 310 337
1959 360 342 406 396 420 472 548 559 463 407 362 405
1960 417 391 419 461 472 535 622 606 508 461 390 432
# standard deviation for each year
flights_wide.std(axis=1)
year
1949 13.720147
1950 19.070841
1951 18.438267
1952 22.966379
1953 28.466887
1954 34.924486
1955 42.140458
1956 47.861780
1957 57.890898
1958 64.530472
1959 69.830097
1960 77.737125
dtype: float64
Plots
may_flights has one observation per year, so no CI is shown.
sns.lineplot(data=may_flights, x="year", y="passengers")
sns.barplot(data=may_flights, x='year', y='passengers')
flights_wide shows there are twelve observations for each year, so the CI shows when all of flights is plotted.
sns.lineplot(data=flights, x="year", y="passengers")
sns.barplot(data=flights, x='year', y='passengers')

Calculating mean values in dataframe and adding to new columns

I need to calculate average values (row wise without index) of columns with constant step.
I have already done a simple operation for the first 4 columns. It works nicely. After that I have created a list with column names (for storing average values) for dataframe. I have found out that I can do this using apply and lambda. I have tried many variants to get a result, but I have not found a solution.
data= np.arange(400).reshape(20,20)
df=pd.DataFrame(data=data)
df.columns=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T']
df['A1_avg'] = df[['A', 'B', 'C', 'D']].mean(axis=1)
colnames_avg=['A1_avg', 'A2_avg', 'A3_avg', 'A4_avg', 'A5_avg']
df.head()
I have tried this code for generating 5 extra columns containing the average of several subsets of data:
df[colnames_avg]=df[colnames_avg].applymap(lambda x: df[['A', 'B', 'C', 'D'], ['E', 'F', 'G', 'H'], ['I', 'J', 'K', 'L'],['M', 'N', 'O', 'P'],['Q', 'R', 'S', 'T']].mean(axis=1)
Is it possible to do this with the range function with a predefined step (e.g. 4)?
I would do that as follows in a loop, going over the columns and cutting them into groups of 4 columns each (the last group might be smaller):
cols=list(df.columns)
while len(cols) > 0:
group= cols[:4]
cols= cols[4:]
df['mean_' + '_'.join(group)]= df[group].mean(axis='columns')
The result looks like
df[[col for col in df if col.startswith('mean_')]]
mean_A_B_C_D mean_E_F_G_H mean_I_J_K_L mean_M_N_O_P mean_Q_R_S_T
0 1.5 5.5 9.5 13.5 17.5
1 21.5 25.5 29.5 33.5 37.5
2 41.5 45.5 49.5 53.5 57.5
3 61.5 65.5 69.5 73.5 77.5
4 81.5 85.5 89.5 93.5 97.5
5 101.5 105.5 109.5 113.5 117.5
...
If you want result columns like A1..., just add a counter variable in the loop and use 'A{}'.format(i) as the column name.
Method 1: numpy.split & DataFrame.loc:
We can split your columns into evenly size chunks and then use .loc to create the new columns:
for idx, chunk in enumerate(np.split(df.columns, len(df.columns)/4)):
df[f'A{idx+1}_avg'] = df.loc[:, chunk].mean(axis=1)
Output
A B C D E F G H I J ... P Q R S T A1_avg A2_avg A3_avg A4_avg A5_avg
0 0 1 2 3 4 5 6 7 8 9 ... 15 16 17 18 19 1.5 5.5 9.5 13.5 17.5
1 20 21 22 23 24 25 26 27 28 29 ... 35 36 37 38 39 21.5 25.5 29.5 33.5 37.5
2 40 41 42 43 44 45 46 47 48 49 ... 55 56 57 58 59 41.5 45.5 49.5 53.5 57.5
3 60 61 62 63 64 65 66 67 68 69 ... 75 76 77 78 79 61.5 65.5 69.5 73.5 77.5
4 80 81 82 83 84 85 86 87 88 89 ... 95 96 97 98 99 81.5 85.5 89.5 93.5 97.5
5 100 101 102 103 104 105 106 107 108 109 ... 115 116 117 118 119 101.5 105.5 109.5 113.5 117.5
6 120 121 122 123 124 125 126 127 128 129 ... 135 136 137 138 139 121.5 125.5 129.5 133.5 137.5
7 140 141 142 143 144 145 146 147 148 149 ... 155 156 157 158 159 141.5 145.5 149.5 153.5 157.5
8 160 161 162 163 164 165 166 167 168 169 ... 175 176 177 178 179 161.5 165.5 169.5 173.5 177.5
9 180 181 182 183 184 185 186 187 188 189 ... 195 196 197 198 199 181.5 185.5 189.5 193.5 197.5
10 200 201 202 203 204 205 206 207 208 209 ... 215 216 217 218 219 201.5 205.5 209.5 213.5 217.5
11 220 221 222 223 224 225 226 227 228 229 ... 235 236 237 238 239 221.5 225.5 229.5 233.5 237.5
12 240 241 242 243 244 245 246 247 248 249 ... 255 256 257 258 259 241.5 245.5 249.5 253.5 257.5
13 260 261 262 263 264 265 266 267 268 269 ... 275 276 277 278 279 261.5 265.5 269.5 273.5 277.5
14 280 281 282 283 284 285 286 287 288 289 ... 295 296 297 298 299 281.5 285.5 289.5 293.5 297.5
15 300 301 302 303 304 305 306 307 308 309 ... 315 316 317 318 319 301.5 305.5 309.5 313.5 317.5
16 320 321 322 323 324 325 326 327 328 329 ... 335 336 337 338 339 321.5 325.5 329.5 333.5 337.5
17 340 341 342 343 344 345 346 347 348 349 ... 355 356 357 358 359 341.5 345.5 349.5 353.5 357.5
18 360 361 362 363 364 365 366 367 368 369 ... 375 376 377 378 379 361.5 365.5 369.5 373.5 377.5
19 380 381 382 383 384 385 386 387 388 389 ... 395 396 397 398 399 381.5 385.5 389.5 393.5 397.5
Method 2: .range & iloc:
We can create a range for each 4 columns, then use iloc to acces each slice of your dataframe and calculate the mean and at the same time create your new column:
slices = range(0, len(df.columns)+1, 4)
for idx, rng in enumerate(slices):
if idx > 0:
df[f'A{idx}_avg'] = df.iloc[:, slices[idx-1]:slices[idx]].mean(axis=1)
Output
A B C D E F G H I J ... P Q R S T A1_avg A2_avg A3_avg A4_avg A5_avg
0 0 1 2 3 4 5 6 7 8 9 ... 15 16 17 18 19 1.5 5.5 9.5 13.5 17.5
1 20 21 22 23 24 25 26 27 28 29 ... 35 36 37 38 39 21.5 25.5 29.5 33.5 37.5
2 40 41 42 43 44 45 46 47 48 49 ... 55 56 57 58 59 41.5 45.5 49.5 53.5 57.5
3 60 61 62 63 64 65 66 67 68 69 ... 75 76 77 78 79 61.5 65.5 69.5 73.5 77.5
4 80 81 82 83 84 85 86 87 88 89 ... 95 96 97 98 99 81.5 85.5 89.5 93.5 97.5
5 100 101 102 103 104 105 106 107 108 109 ... 115 116 117 118 119 101.5 105.5 109.5 113.5 117.5
6 120 121 122 123 124 125 126 127 128 129 ... 135 136 137 138 139 121.5 125.5 129.5 133.5 137.5
7 140 141 142 143 144 145 146 147 148 149 ... 155 156 157 158 159 141.5 145.5 149.5 153.5 157.5
8 160 161 162 163 164 165 166 167 168 169 ... 175 176 177 178 179 161.5 165.5 169.5 173.5 177.5
9 180 181 182 183 184 185 186 187 188 189 ... 195 196 197 198 199 181.5 185.5 189.5 193.5 197.5
10 200 201 202 203 204 205 206 207 208 209 ... 215 216 217 218 219 201.5 205.5 209.5 213.5 217.5
11 220 221 222 223 224 225 226 227 228 229 ... 235 236 237 238 239 221.5 225.5 229.5 233.5 237.5
12 240 241 242 243 244 245 246 247 248 249 ... 255 256 257 258 259 241.5 245.5 249.5 253.5 257.5
13 260 261 262 263 264 265 266 267 268 269 ... 275 276 277 278 279 261.5 265.5 269.5 273.5 277.5
14 280 281 282 283 284 285 286 287 288 289 ... 295 296 297 298 299 281.5 285.5 289.5 293.5 297.5
15 300 301 302 303 304 305 306 307 308 309 ... 315 316 317 318 319 301.5 305.5 309.5 313.5 317.5
16 320 321 322 323 324 325 326 327 328 329 ... 335 336 337 338 339 321.5 325.5 329.5 333.5 337.5
17 340 341 342 343 344 345 346 347 348 349 ... 355 356 357 358 359 341.5 345.5 349.5 353.5 357.5
18 360 361 362 363 364 365 366 367 368 369 ... 375 376 377 378 379 361.5 365.5 369.5 373.5 377.5
19 380 381 382 383 384 385 386 387 388 389 ... 395 396 397 398 399 381.5 385.5 389.5 393.5 397.5
[20 rows x 25 columns]

Python and Sqlite3, transforming data text file to sql database

So I've been given an assignment/Challenge to complete but I just don't know whee to start with it I've got experience with Python but not with using databases and data transformation onto the description.
So here is a snippet of my text file I've been given:
Grid-ref= 1, 148
3020 2820 3040 2880 1740 1360 980 990 1410 1770 2580 2630
3020 2820 3040 2880 1740 1360 980 990 1410 1770 2580 2630
3020 2820 3040 2880 1740 1360 980 990 1410 1770 2580 2630
3020 2820 3040 2880 1740 1360 980 990 1410 1770 2580 2630
3020 2820 3040 2880 1740 1360 980 990 1410 1770 2580 2630
3020 2820 3040 2880 1740 1360 980 990 1410 1770 2580 2630
3020 2820 3040 2880 1740 1360 980 990 1410 1770 2580 2630
3020 2820 3040 2880 1740 1360 980 990 1410 1770 2580 2630
3020 2820 3040 2880 1740 1360 980 990 1410 1770 2580 2630
3020 2820 3040 2880 1740 1360 980 990 1410 1770 2580 2630
Grid-ref= 1, 311
490 290 280 230 200 250 440 530 460 420 530 450
490 290 280 230 200 250 440 530 460 420 530 450
490 290 280 230 200 250 440 530 460 420 530 450
490 290 280 230 200 250 440 530 460 420 530 450
490 290 280 230 200 250 440 530 460 420 530 450
490 290 280 230 200 250 440 530 460 420 530 450
490 290 280 230 200 250 440 530 460 420 530 450
490 290 280 230 200 250 440 530 460 420 530 450
490 290 280 230 200 250 440 530 460 420 530 450
490 290 280 230 200 250 440 530 460 420 530 450
Grid-ref= 1, 312
460 280 260 220 190 240 430 520 450 400 520 410
460 280 260 220 190 240 430 520 450 400 520 410
460 280 260 220 190 240 430 520 450 400 520 410
460 280 260 220 190 240 430 520 450 400 520 410
460 280 260 220 190 240 430 520 450 400 520 410
460 280 260 220 190 240 430 520 450 400 520 410
460 280 260 220 190 240 430 520 450 400 520 410
460 280 260 220 190 240 430 520 450 400 520 410
460 280 260 220 190 240 430 520 450 400 520 410
460 280 260 220 190 240 430 520 450 400 520 410
So from this i must then create a database containing 4 columns like so:
Xref Yref Date Value
1 148 1,1,2000 3020
1 148 1,2,2000 2820
I hope you can see the pattern so grid-ref= 1, 148 are my X & Y co-ords then each value is obviously the value but i need to iterate through and for each value it then gives it the new date which is just the 1st of each month for 10 years.
So far I have this code which i know isn't much it's a start.
import os
import csv
import sqlite3
f_path = os.path.dirname(os.path.abspath(__file__)) + "/data/"
db = sqlite3.connect('output.db')
cursor = db.cursor()
cursor.execute('CREATE TABLE Data (Xref, Yref, Date, Value)')
date = 2000 - 2010
grid = 'Xref, Yref'
with open(f_path + "data.to.use.txt") as file_read:
for row in csv.DictReader(file_read):
cursor.execute('''INSERT INTO Data
VALUES (:Xref, :Yref, :Date, :Value)''', row)
db.commit()
db.close()
Thank you for all feedback and guidance, I'm in unfamiliar territory with this type of task and hope you can help.
you could try the below code. I am not quite not clear with date requirement . So I just added a month for each entry
from datetime import date,datetime
from dateutil.relativedelta import relativedelta
Xref=''
Yref=''
date =datetime.strptime('2000-01-01', '%Y-%m-%d')
with open('C:\Users\shmathew\Desktop\Sample\sample.txt') as file_read:
for row in file_read:
print row
if 'Grid-ref' in row:
Xref = row.split(',')[0].split('= ')[1]
Yref = row.split(',')[1]
else:
for Value in row.split(' '):
date = date + relativedelta(months=+1)
print Xref.strip(),Yref.strip(),date,Value.strip()
Sample output
490 290 280 230 200 250 440 530 460 420 530 450
1 311 2009-08-01 00:00:00 490
1 311 2009-09-01 00:00:00 290
1 311 2009-10-01 00:00:00 280
1 311 2009-11-01 00:00:00 230
1 311 2009-12-01 00:00:00 200
1 311 2010-01-01 00:00:00 250
1 311 2010-02-01 00:00:00 440
1 311 2010-03-01 00:00:00 530
1 311 2010-04-01 00:00:00 460
1 311 2010-05-01 00:00:00 420
1 311 2010-06-01 00:00:00 530
1 311 2010-07-01 00:00:00 450
490 290 280 230 200 250 440 530 460 420 530 450
1 311 2010-08-01 00:00:00 490
1 311 2010-09-01 00:00:00 290
1 311 2010-10-01 00:00:00 280
1 311 2010-11-01 00:00:00 230
1 311 2010-12-01 00:00:00 200
1 311 2011-01-01 00:00:00 250
1 311 2011-02-01 00:00:00 440
1 311 2011-03-01 00:00:00 530
1 311 2011-04-01 00:00:00 460
1 311 2011-05-01 00:00:00 420
1 311 2011-06-01 00:00:00 530
1 311 2011-07-01 00:00:00 450
490 290 280 230 200 250 440 530 460 420 530 450
1 311 2011-08-01 00:00:00 490
1 311 2011-09-01 00:00:00 290
1 311 2011-10-01 00:00:00 280
1 311 2011-11-01 00:00:00 230
1 311 2011-12-01 00:00:00 200
1 311 2012-01-01 00:00:00 250
1 311 2012-02-01 00:00:00 440
1 311 2012-03-01 00:00:00 530
1 311 2012-04-01 00:00:00 460
1 311 2012-05-01 00:00:00 420
1 311 2012-06-01 00:00:00 530
1 311 2012-07-01 00:00:00 450

Categories

Resources