Reputation: 159
I have multiple csv file that looks something like this:
>>> print(df)
x x.1 x.2 x.3 ... Unnamed: 33 Unnamed: 34 Unnamed: 35 Unnamed: 36
0 x x x x ... x x x x
1 x x x x ... x x x x
2 x x x x ... NaN NaN NaN NaN
3 x x x x ... NaN NaN NaN NaN
4 x x x x ... NaN NaN NaN NaN
5 x x x x ... NaN NaN NaN NaN
6 x x x x ... NaN NaN NaN NaN
7 x x x x ... NaN NaN NaN NaN
8 x x x x ... NaN NaN NaN NaN
9 x x x x ... NaN NaN NaN NaN
10 x x x x ... NaN NaN NaN NaN
11 x x x x ... NaN NaN NaN NaN
12 x x x x ... NaN NaN NaN NaN
13 x x x x ... NaN NaN NaN NaN
14 A A A A ... NaN NaN NaN NaN
15 B B B B ... NaN NaN NaN NaN
16 C C C C ... NaN NaN NaN NaN
17 D D D D ... NaN NaN NaN NaN
18 E E E E ... NaN NaN NaN NaN
19 F F F F ... NaN NaN NaN NaN
20 x x x x ... NaN NaN NaN NaN
21 x x x x ... NaN NaN NaN NaN
22 x x x x ... NaN NaN NaN NaN
23 x x x x ... NaN NaN NaN NaN
24 x x x x ... NaN NaN NaN NaN
[25 rows x 37 columns]
There are a lot of different types of data in this csv file, but the only data I require is that labelled A-F
. I have a large amount of these csv files, so what I want to do is merge them together but only with the data that I want from them.
I have two approaches, one better than the other.
(1) The data I want pretty much always occurs on row 14-19
and is 4 columns long. So what I was thinking each time I read in one of these csv files I can skip rows above 14
and below 19
however I am unsure how to do this?
Something like this data = pd.read_csv(file,skiprows=[0:14])
however I also want to skip any rows after 19? Is there a way to just load in rows 14-19
with just columns 0-4
?
(2) My second idea I am not sure if possible but in case the data doesn't appear on row 14-19
in one file, maybe I can get python to somehow search for the data I want and that will get rid of any errors of taking the wrong rows?
Any help is appreciated, thanks!
Upvotes: 0
Views: 269
Reputation: 506
pandas has an additional param, nrows
, which can be used to read only a specified number of rows
>>> import pandas as pd
>>> df = pd.read_csv(filename, skiprows=list(range(14)), n_rows=6)
>>> df
x x.1 x.2 x.3 ... Unnamed: 33 Unnamed: 34 Unnamed: 35 Unnamed: 36
0 A A A A ... NaN NaN NaN NaN
1 B B B B ... NaN NaN NaN NaN
2 C C C C ... NaN NaN NaN NaN
3 D D D D ... NaN NaN NaN NaN
4 E E E E ... NaN NaN NaN NaN
5 F F F F ... NaN NaN NaN NaN
Upvotes: 2
Reputation: 3173
following your second idea 'in case the data doesn't appear on row 14-19 in one file':
#getting the desired rows
df_desired = data.loc[ (data['x'] == 'A') | (data['x'] == 'B')|(data['x'] == 'C') | (data['x'] == 'E')| (data['x'] == 'F')]
#getting the first 4 columns
df=df.ix[:,[0:4]]
Upvotes: 1