Short answer: Use Position
to locate your data then use Part
to extract it. For example, we can evaluate this code
url = "https://www.census.gov/population/international/data/worldpop/table_history.php";
page = Import[url, "Data"];
Position[page, "10000 BC"]
(* {{3, 1, 2, 2, 1, 1}} *)
Based on those subscripts, we can look at page[[3]]
then look at page[[3,1]]
, etc. Finally we decide to look at
table = page[[3, 1, 2 ;;, 2]][[1]];
table[[All, 1 ;; 3]] // TableForm
(*
{
{"10000 BC", 1, 10},
{"8000 BC", 5, 5},
{"6500 BC", 5, 10},
{"5000 BC", 5, 20},
{"4000 BC", 7, 7}
} *)
The actual data goes down farther than shown.
Explanation of the Code (beginners only)
Detailed descriptions of what the Part command
and the Position command
do can be found in the documentation. The Part command is usually written as [[ ]]
. There is a lot of information in the Mathematica documentation about searching in lists. You might start with Testing and Searching List Elements, but look at all of the related guides and tutorials also. What you need to know is not in just one place.
In the above code, we separated the URL string from the Import
command for readability. Import
returns a nested list, which is a list of lists. If the evaluate the command Length[page]
, we find that Import
has given us a list contain 3 more lists.
When we evaluate Position[ page, "10000 BC"]
we get back another nested list, {{3, 1, 2, 3, 1, 1}}
. This means the data we are looking for can be found somewhere in the 3rd element of page
, which is itself a list. Then, in that 3rd element, our data is somewhere in 1 element, which is another list. Within that list, our data is some where in 2nd element, which is still another list.
Note that if we evaluated Position[ page, 10000 ]
, Mathematica would look for the integer 10000 and not find it. Our data is the string "10000 BC".
We could examine all of the elements by using Part
and looking at a = page[[3]]
and then b = a[[1]]
and then c = b[[2]]
, etc. We know what subscripts to use, because Position
has told us exactly where to find our data.
To find a range of data, we use ;; in our subscripts. The meaning can be found in the documentation for Part
.