read csv and Iterate through 10 row blocks - python

I am trying to read a CSV file and Iterate through 10-row blocks.
The data is quite unusual, with two columns and 10-row blocks.
57485 rows x 2 columns in the format below:
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
Every 10 rows consist of a grid reference and two records X/Y ref.
The grid reference and X value is in column 1, the Y value is in column 2, and then 9 rows with 12 columns, in column one.
The blocks (x) 0 - 9, represent months (Jan - December
The blocks (y) 0 - 9, represent years (1991-2000)
So for 0, is 1991
3020 is January 1991, 2820 is February 1991
Grid-ref = 1 (X),148 (Y)
The code below reads 10 rows, but keeps repeating the first row in all following 10-row blocks??
I don't understand why it keeps repeating the first row??
Any suggestions to resolve this would be appreciated..
## Python 3.6
## Read in the datasets (they are in CSV format)
data = pd.read_csv('cru-ts-2-10-1991-2000-cutdown.csv', skiprows=5, na_values = [-999] )
## View data >> 57485 rows x 2 columns
#print(data)
#print(len(data)) ## len = 57485
## header = pd.MultiIndex.from_product([['Grid-ref', 'Xref', 'Yref'], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' ] ])
# df = pd.DataFrame(np.random.randn(10, 11),
# index=['1991','1992','1993','1994','1995', '1996', '1997', '1998', '1999', '2000', '2001'],
# columns=header)
# print(data.head(10)) ## prints chunks of 10 rows
def chunker(seq, size):
return (seq[pos:pos + size] for pos in range(0, len(seq), size))
for group in chunker(data, 10):
print(group)
The first two block:
Grid-ref= 1 148
0 3020 2820 3040 2880 1740 1360 980 990 1410 ... NaN
1 3020 2820 3040 2880 1740 1360 980 990 1410 ... NaN
2 3020 2820 3040 2880 1740 1360 980 990 1410 ... NaN
3 3020 2820 3040 2880 1740 1360 980 990 1410 ... NaN
4 3020 2820 3040 2880 1740 1360 980 990 1410 ... NaN
5 3020 2820 3040 2880 1740 1360 980 990 1410 ... NaN
6 3020 2820 3040 2880 1740 1360 980 990 1410 ... NaN
7 3020 2820 3040 2880 1740 1360 980 990 1410 ... NaN
8 3020 2820 3040 2880 1740 1360 980 990 1410 ... NaN
9 3020 2820 3040 2880 1740 1360 980 990 1410 ... NaN
Grid-ref= 1 148
10 Grid-ref= 1 311.0
11 490 290 280 230 200 250 440 530 460 ... NaN
12 490 290 280 230 200 250 440 530 460 ... NaN
13 490 290 280 230 200 250 440 530 460 ... NaN
14 490 290 280 230 200 250 440 530 460 ... NaN
15 490 290 280 230 200 250 440 530 460 ... NaN
16 490 290 280 230 200 250 440 530 460 ... NaN
17 490 290 280 230 200 250 440 530 460 ... NaN
18 490 290 280 230 200 250 440 530 460 ... NaN
19 490 290 280 230 200 250 440 530 460 ... NaN

Pandas is good for uniform columnar data. If your input isn't uniform, you can preprocess it and then load the dataframe. This one is easy, all you need to do is scan for grid headers and remove them. Since the data itself is numeric, separated by whitespace, a simple split will parse it. This example creates a list but if the dataset is large, it may be reasonable to write to an intermediate file instead.
import csv
import re
import pandas as pd
grid_re = re.compile(r"Grid-ref=\s*(\d+),(\d+)")
with open('test.csv') as fobj:
table = []
try:
while True:
# find next block
for line in fobj:
match = grid_re.search(line)
if match:
grid_xy = list(match.groups())
break
else:
raise StopIteration()
for _ in range(10):
line = next(fobj)
# add row plus grid columns
table.append(line.strip().split() + grid_xy)
except StopIteration:
pass
df = pd.DataFrame(table)
print(df)

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)

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]

Unexpected Fourier Transform result in Python Numpy

I am having a problem plotting the fourier transform of a data series (Y = intensity, X = wavelength). The goal is to remove the sinusoidal oscillation but applying a notch filter to the fourier transform of the data, followed by another fourier transform.
Here's the original data series:
df = pd.read_csv(file, sep='\t', skiprows=7)
df.plot(x='X', y='Y')
And after doing the fourier transform:
df['spectrum'] = np.fft.fft(df[['Y']]).real
df['freq'] = np.fft.fftfreq(len(df.index), 1)
df.plot(x='freq', y='spectrum')
Problem: Why did it plot nothing? Was the FFT done incorrectly?
Data
X Y
500 383.800049
501 -407.599976
502 435
503 -446.8
504 442.800049
505 -419.399963
506 425.200073
507 -423.599976
508 387.400024
509 -438.199951
510 473.599976
511 -446.399963
512 392.599976
513 -393
514 414.599976
515 -392.199951
516 469.599976
517 -359.8
518 544.6
519 -365.399963
520 535.2001
521 -361.399963
522 527.4
523 -389.399963
524 556.6
525 -399
526 534.800049
527 -360.8
528 689.2001
529 -206.399963
530 904.2001
531 51
532 1166.00012
533 230.200073
534 1338.4
535 254.200073
536 1192.6
537 149
538 925.7999
539 -119.599976
540 745.800049
541 -329.399963
542 602.2001
543 -344
544 469.599976
545 -453.599976
546 384.800049
547 -485.599976
548 334.599976
549 -506
550 305.800049
551 -525.199951
552 412.400024
553 -419
554 404.599976
555 -466.199951
556 466.400024
557 -437.399963
558 478.400024
559 -389
560 478.599976
561 -391.199951
562 461.200073
563 -366
564 481.599976
565 -414.399963
566 525.800049
567 -379.8
568 495.200073
569 -368.599976
570 518.800049
571 -388
572 485
573 -412.599976
574 519.4
575 -383
576 656.2001
577 -334
578 609.800049
579 -304.399963
580 563.800049
581 -352.199951
582 567.2001
583 -372.399963
584 463.400024
585 -362.399963
586 516.2001
587 -309.199951
588 548.4
589 -340.8
590 627
591 -352.199951
592 686.2001
593 -302.599976
594 736.4
595 -301.399963
596 716.800049
597 -337.399963
598 642.2001
599 -332.599976
600 646.800049
601 -316.399963
602 733.800049
603 -274.199951
604 715.800049
605 -325.8
606 683.6
607 -352.8
608 581
609 -352.399963
610 611.2001
611 -360.8
612 555.800049
613 -348.199951
614 583.4
615 -416.8
616 539.4
617 -337.199951
618 607.4
619 -310.8
620 542.800049
621 -300.8
622 534.4
623 -295.399963
624 603.6
625 -348
626 599.800049
627 -252.199951
628 576.800049
629 -309
630 703.4
631 -300.399963
632 621.800049
633 -345.199951
634 586.2001
635 -314.8
636 615.2001
637 -352.399963
638 623.800049
639 -281.399963
640 636.2001
641 -367
642 546
643 -295
644 595.4
645 -342.399963
646 554.6
647 -358.399963
648 567.4
649 -379
650 581.2001
651 -383.8
652 497.400024
653 -343.399963
654 588
655 -379
656 524.6
657 -365.8
658 506.200073
659 -413.8
660 554.800049
661 -391.8
662 541.800049
663 -409.199951
664 573
665 -390.399963
666 535
667 -373.8
668 513.2001
669 -376
670 538.4
671 -391
672 566.2001
673 -424.199951
674 493.200073
675 -471.199951
676 408.800049
677 -454
678 289
679 -612
680 252.200073
681 -413.8
682 465.800049
683 -251.399963
684 708.2001
685 -134.599976
686 860.2001
687 -56.4000244
688 907.7999
689 23.2000732
690 935.2001
691 9.599976
692 960.0001
693 201.599976
694 1355.6
695 78.4000244
696 1265.79993
697 0.200073242
698 1283.6
699 -11
700 1103.20007
701 -50.4000244
702 1067.00012
703 -35
704 1080.79993
705 -67.5999756
706 1025.6
707 -155
708 945.4
709 -129.399963
710 835.800049
711 -230.599976
712 722.800049
713 -267.199951
714 743.2001
715 -281.199951
716 675
717 -278.599976
718 612.800049
719 -283.399963
720 687
721 -296.199951
722 626.6
723 -292.599976
724 674.800049
725 -264
726 663.800049
727 -272.199951
728 644.6
729 -266
730 608.4
731 -293
732 660.2001
733 -291.599976
734 690.4
735 -274.399963
736 646.2001
737 -233
738 645.800049
739 -206.599976
740 641.4
741 -222.599976
742 671.6
743 -282.199951
744 664.6
745 -207.399963
746 689
747 -277.8
748 662
749 -236.199951
750 710.4
751 -198.399963
752 747.2001
753 -227.599976
754 704
755 -278.199951
756 731
757 -237
758 698.4
759 -284
760 613
761 -289.8
762 638.4
763 -297.599976
764 696.800049
765 -245.799988
766 628.2001
767 -218.399963
768 657
769 -276.8
770 680.4
771 -256
772 656.800049
773 -305.399963
774 613.800049
775 -354.399963
776 755.2001
777 -282.199951
778 778.4
779 -267.199951
780 691.800049
781 -261.399963
782 732.4
783 -287.8
784 690.2001
785 -292
786 711.2001
787 -262.199951
788 751.800049
789 -286.8
790 680.800049
791 -273
792 688.800049
793 -256.199951
794 713.6
795 -293.199951
796 679.800049
797 -324.8
798 607
799 -345.199951
800 548.4
801 -339.8
802 550.4
803 -359.399963
804 557.2001
805 -326.399963
806 536
807 -409.599976
808 462.400024
809 -453
810 466.800049
811 -450.599976
812 531
813 -384.8
814 585
815 -291.399963
816 608.6
817 -380.199951
818 530.4
819 -387.199951
820 539.4
821 -327
822 597.2001
823 -321.599976
824 284.200073
825 -586
826 211.800049
827 -509
828 220.200073
829 -586
830 186.200073
831 -577.399963
832 222.200073
833 -538.8
834 200.200073
835 -598.199951
836 196.599976
837 -571.8
838 148.599976
839 -612.399963
840 193.400024
841 -589.399963
842 206.200073
843 -593
844 144.599976
845 -572.399963
846 141.400024
847 -598
848 156.200073
849 -604.8
850 160.800049
851 -562
852 87.5999756
853 -649
854 84.5999756
855 -649
856 166.400024
857 -537.6
858 207
859 -549.8
860 213.599976
861 -543.6
862 193
863 -555.199951
864 234.800049
865 -563.6
866 221.599976
867 -503
868 196.599976
869 -570.8
870 224.200073
871 -556.8
872 193.400024
873 -545.399963
874 163.599976
875 -584.399963
876 598
877 -432.399963
878 497.599976
879 -440.8
880 410.200073
881 -513.399963
882 389.400024
883 -519
884 324
885 -554.8
886 273.800049
887 -529.8
888 255.400024
889 -615
890 219.599976
891 -537.399963
892 194.599976
893 -464
894 517.4
895 -380.199951
896 498.400024
897 -469.199951
898 425.400024
899 -394.199951
900 467.200073
901 -453.399963
902 522.6
903 -383.8
904 557
905 -365.399963
906 526.6
907 -342.8
908 544.4
909 -367.8
910 534.4
911 -429
912 565
913 -383.599976
914 483.599976
915 -371.199951
916 562
917 -374.199951
918 521
919 -517.8
920 425.200073
921 -469.599976
922 492.800049
923 -467.399963
924 409.200073
925 -455.199951
926 384.800049
927 -481.199951
928 408.200073
929 -449.8
930 503
931 -429.599976
932 540.2001
933 -432.8
934 476.800049
935 -420
936 428.599976
937 -547.399963
938 124.200073
939 -620.399963
940 130.599976
941 -583.8
942 113.400024
943 -617.399963
944 141
945 -606.399963
946 107
947 -640
948 98.4000244
949 -604.8
950 120.400024
951 -585
952 260.800049
953 -503
954 261.800049
955 -537
956 248.800049
957 -536.199951
958 211.800049
959 -500.8
960 255.400024
961 -501.399963
962 238.599976
963 -529
964 254.800049
965 -506.599976
966 226.400024
967 -476.599976
968 224.200073
969 -504.399963
970 141
971 -608.199951
972 146.800049
973 -600.399963
974 161
975 -579.399963
976 274
977 -519.6
978 297.400024
979 -542.8
980 256
981 -520.8
982 280.599976
983 -544.8
984 284.200073
985 -522
986 277.599976
987 -492.199951
988 277
989 -511.599976
990 246.599976
991 -537.399963
992 301.800049
993 -474.8
994 268.599976
995 -503
996 253.200073
997 -506.8
998 265.599976
999 -495.399963
1000 234.599976
1001 -519.399963
1002 246.200073
1003 -489
1004 306
1005 -533.6
1006 296
1007 -502.199951
1008 293.800049
1009 -494.199951
1010 304
1011 -461.199951
1012 279.200073
1013 -526.199951
1014 279.200073
1015 -473.8
1016 293.599976
1017 -460
1018 307.400024
1019 -520.6
1020 337.200073
1021 -503.599976
1022 284
1023 -516.8
1024 326.400024
1025 -479.8
1026 337.200073
1027 -503
1028 329.800049
1029 -467.599976
1030 322.800049
1031 -499.8
1032 351
1033 -490.199951
1034 354
1035 -474
1036 343.800049
1037 -472.8
1038 356.400024
1039 -457.8
1040 364
1041 -465.599976
1042 434
1043 -438.399963
1044 418.800049
1045 -412
1046 412.400024
1047 -455.399963
1048 452.200073
1049 -457.8
1050 394.200073
1051 -427
1052 422.599976
1053 -333.8
1054 561
1055 -351.199951
1056 503
1057 -470.199951
1058 508
1059 -448.599976
1060 484.800049
1061 -392.199951
1062 499.200073
1063 -424.599976
1064 473
1065 -417.599976
1066 518.800049
1067 -389.199951
1068 539.6
1069 -420.399963
1070 475.599976
1071 -385
1072 515.2001
1073 -388.199951
1074 521.4
1075 -414.599976
1076 462.800049
1077 -398.199951
1078 468.400024
1079 -468.599976
1080 427.400024
1081 -481.199951
1082 284.400024
1083 -608.199951
1084 175
1085 -627.8
1086 135
1087 -659.199951
1088 136.400024
1089 -623.199951
1090 143.599976
1091 -600
1092 147.800049
1093 -599.6
1094 113
1095 -614.8
1096 141.599976
1097 -642.6
1098 157.400024
1099 -611.399963
1100 147.200073
1101 -610.199951
1102 164.200073
1103 -637.8
1104 146.800049
1105 -581.8
1106 125.800049
1107 -629.6
1108 167
1109 -569
1110 94.20007
1111 -604.6
1112 142.400024
1113 -602.199951
1114 116
1115 -606.8
1116 142.400024
1117 -580
1118 117.200073
1119 -596.399963
1120 145.599976
1121 -620.6
1122 110.599976
1123 -625.8
1124 89.80005
1125 -619
1126 139
1127 -583.199951
1128 146.800049
1129 -593
1130 140.599976
1131 -597.6
1132 148
1133 -650
1134 118.800049
1135 -596.199951
1136 352.400024
1137 -444.199951
1138 381.400024
1139 -492.8
1140 334.400024
1141 -497.399963
1142 347
1143 -484.399963
1144 330.400024
1145 -483.599976
1146 357.599976
1147 -523.199951
1148 315.200073
1149 -503.399963
1150 345.800049
1151 -487.199951
1152 355.400024
1153 -456.599976
1154 370
1155 -497.199951
1156 379.800049
1157 -458.399963
1158 409.400024
1159 -503.599976
1160 320.400024
1161 -459
1162 397.200073
1163 -486.599976
1164 354.599976
1165 -439.8
1166 418.200073
1167 -454.199951
1168 334.599976
1169 -436
1170 341.400024
1171 -469.599976
1172 406.200073
1173 -489.8
1174 384.200073
1175 -479.199951
1176 373.400024
1177 -446
1178 401.800049
1179 -455.599976
1180 344
1181 -471.599976
1182 386.400024
1183 -465.8
1184 363.400024
1185 -480
1186 410.599976
1187 -462.199951
1188 450
1189 -452.8
1190 351.800049
1191 -484.8
1192 393.400024
1193 -439.399963
1194 397
1195 -471.8
1196 426.599976
1197 -381.199951
1198 418.400024
1199 -418
1200 426.800049
1201 -447
1202 366.800049
1203 -431.8
1204 443.400024
1205 -460.8
1206 440.400024
1207 -416.199951
1208 409.599976
1209 -397.199951
1210 427.400024
1211 -394.599976
1212 495.599976
1213 -408.8
1214 470.400024
1215 -421.8
1216 517.800049
1217 -442.399963
1218 527.2001
1219 -399.199951
1220 544.2001
1221 -354
1222 535.4
1223 -358.399963
1224 527.6
1225 -374
1226 599
1227 -392
1228 590.4
1229 -327.8
1230 602.6
1231 -353.199951
1232 650.2001
1233 -369.599976
1234 642
1235 -359
1236 725.800049
1237 -296.599976
1238 734.4
1239 -223.199951
1240 766.4
1241 -287.8
1242 752.2001
1243 -277.199951
1244 828.4
1245 -233.199951
1246 809
1247 -198
1248 773
1249 -228.799988
1250 803.800049
1251 -278
1252 767
1253 -238
1254 859.800049
1255 -238.399963
1256 740.4
1257 -269.599976
1258 742.6
1259 -297.199951
1260 714.800049
1261 -344
1262 616.2001
1263 -342.8
1264 654.2001
1265 -365.199951
1266 660.4
1267 -372.199951
1268 669.2001
1269 -299.599976
1270 667.2001
1271 -345
1272 637
1273 -357.8
1274 646.800049
1275 -381.399963
1276 652.800049
1277 -378.199951
1278 622.4
1279 -347.199951
1280 647.6
1281 -361.599976
1282 646.800049
1283 -371.399963
1284 601.4
1285 -360.199951
1286 630.4
1287 -289.599976
1288 619
1289 -304.199951
1290 672
1291 -368
1292 591.4
1293 -375.399963
1294 590.4
1295 -442
1296 578
1297 -424.199951
1298 626.800049
1299 -384.8
1300 616.6
Three-ish problems.
(1) Compare the following two:
df[['Y']].as_matrix().shape # (801, 1), yours
df['Y'].as_matrix().shape # (801,), better
np.fft.fft says if axis is not provided, the last axis is used. In your code, the FFT of an 801 by 1 array is evaluated along the last dimension, i.e., a 1-point FFT—totally not what you wanted.
Solution: remove one pair of brackets.
(2) With this in place, the output of np.fft.fft is complex, as expected. Instead of taking its real-only component, use it’s absolute value.
(3) Furthermore, it appears that Pandas plot has some problems plotting the output of np.fft.fftfreq because its output goes from [0 ... 0.5 -0.5 ... 0]. Simple solution: use np.fft.fftshift.
Solutions to #2–3:
df['spectrum'] = np.abs(np.fft.fftshift(np.fft.fft(df['Y'])))
df['freq'] = np.fft.fftshift(np.fft.fftfreq(len(df.index), 1))
(Alternative solution to #3: use np.fft.rfft and rfftfreq, since your input data is real.)
Final code:
import pandas as pd
import numpy as np
df = pd.read_csv('dat.csv', sep=',')
df.plot(x='X', y='Y')
df['spectrum'] = np.abs(np.fft.fftshift(np.fft.fft(df['Y'])))
df['freq'] = np.fft.fftshift(np.fft.fftfreq(len(df.index), 1))
df.plot(x='freq', y='spectrum')
Result:
Suggestion: better than np.abs is to use db (decibels). I.e., db = lambda x: 20 * np.log10(np.abs(x)). Alternatively, if that’s not your thing, just plot the y-axis on a log-scale.
Observation: you should be able to remove the high-frequency noisy by low-pass filtering the data, with a cutoff frequency of 0.25 normalized Hz. (Let me know if you have trouble with that.) If I collected this kind of data, I’d worry that my anti-aliasing filter before the ADC wasn’t working—one shouldn’t ever see so much noise right at the Nyquist frequency. If you are getting a lot of aliasing, who knows what the original signal is.

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