Message Boards Message Boards

0
|
6868 Views
|
4 Replies
|
5 Total Likes
View groups...
Share
Share this post:

Retain Only Certain Rows from a Grid/CSV/Table

Posted 10 years ago

Hello,

Tables have 'n1' rows and 'n2' columns. The values of 'n1' & 'n2' can be known in each instance with a little trouble.

I'm importing CSVs and have them in Grid and CSV format within Mathematica, although I can manipulate the format as need be.

I've identified rows that I would like to retain. For example, it may be row 1, 7, 21, 245, and so forth. There are often hundreds of such rows.

I'd like to retain all columns in the tables.

How might I do this? I've tried several approaches and read some stack overflow posts, but haven't yet stumbled upon anything productive. Any help appreciated!

Greg

POSTED BY: Greg
4 Replies
Posted 10 years ago

Look up the function Part. The double brackets below are a way of using Part.

data = Table[{i, j}, {i, 1, 7}, {j, 1, 4}]

(*
{{{1,1},{1,2},{1,3},{1,4}},{{2,1},{2,2},{2,3},{2,4}},{{3,1},{3,2},{3,\
3},{3,4}},{{4,1},{4,2},{4,3},{4,4}},{{5,1},{5,2},{5,3},{5,4}},{{6,1},{\
6,2},{6,3},{6,4}},{{7,1},{7,2},{7,3},{7,4}}}
*)

(* take rows 1, 3, 4 *)
data[[{1, 3, 4}]]

(*
{{{1,1},{1,2},{1,3},{1,4}},{{3,1},{3,2},{3,3},{3,4}},{{4,1},{4,2},{4,\
3},{4,4}}}
*)
POSTED BY: David Keith
Posted 10 years ago

The table is a list of lists. When you write data[[2]], you are asking for the 2nd part. At the top level, data is a list, so the 2nd part is the 2nd row, which is also a list. If you look up Part, you will see that giving it a list, as in {1,3,4}, asks for a list of those parts, which is the rows.

There are more complicated ways to use Part. data[[2,3]] asks for the element in the 3rd column of the 2nd row. data[[All,2]] asks for the 2nd element of All the rows.

Notice that the only thing that distinguishes rows from columns is convention. By convention the first index of a table or matrix designates a row, and the second a column. Following that convention, Mathematica displays a table that way.

POSTED BY: David Keith

hi David--

cool answer. Thanks! why does doing it this way (with the data[[{1, 3, 4}]] ) bring out the rows, as opposed for example instead of the columns? I am new to Mathematica but the simplicity and power of this language is incredible. Just trying to learn more!

-Joaquin

POSTED BY: Joaquin Roibal

Great! Thanks for the reply.

POSTED BY: Joaquin Roibal
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract