Shared posts

24 Oct 17:43

Introducing Pandas

by Abder-Rahman Ali

In this tutorial I will give a basic introduction to pandas. Oh, I don't mean the animal panda, but a Python library!

As mentioned on the pandas website:

pandas is an open source, BSD-licensed library providing high-performance, easy-to-use data structures and data analysis tools for the Python programming language.

Thus, pandas is a data analysis library that has the data structures we need to cleanse raw data into a form which is suitable for analysis (i.e. tables). It is important to note here that since pandas performs important tasks such as aligning data for comparison and merging of data sets, handling of missing data, etc., it has become a de facto library for high-level data processing in Python (i.e. statistics). Well, pandas was originally designed to handle financial data, provided that the common alternative is using a spreadsheet (i.e. Microsoft Excel).

The basic data structure of pandas is called DataFrame, which is an ordered collection of columns with names and types, thus looking like a database table where a single row represents a single case (example) and columns represent particular attributes. It should be noted here that the elements in various columns may be of different types.

So, the bottom line is that the pandas library provides us with the data structures and functions necessary for data analysis.

Installing Pandas

Let's now see how we can install pandas on our machines and use it for data analysis. The easiest way to install pandas and avoid any dependency issues is by using Anaconda which pandas comes part of. As mentioned on the Anaconda download page:

Anaconda is a completely free Python distribution (including for commercial use and redistribution). It includes more than 400 of the most popular Python packages for science, math, engineering, and data analysis

The Anaconda distribution is cross-platform, meaning that it can be installed on OS X, Windows, and Linux machines. I'm going to use the OS X installer since I'm working on a Mac OS X El Capitan machine, but of course you can choose the suitable installer for your operating system. I will go with the graphical installer (be careful, it is 339 MB).

Anaconda Mac OS X graphical installer
Anaconda Mac OS X Graphical Installer

After downloading the installer, simply walk through the simple installation wizard steps and you are all set!

All we need to do now in order to use pandas is to import the package as follows:

import pandas as pd

Pandas Data Structures

I have mentioned one of the three pandas data structures above, the DataFrame. I will describe this data structure in this section in addition to the other pandas data structure, Series. There is another data structure called Panel, but I will not describe it in this tutorial as it is not so frequently used, as mentioned in the documentationDataFrame is a 2D data structure, Series is a 1D data structure, and Panel is a 3D and higher data structure.

DataFrame

The DataFrame is a tabular data structure which is composed of ordered columns and rows. To make things clearer, let's look at the example of creating a DataFrame (table) from a dictionary of lists. The following example shows a dictionary consisting of two keys, Name and Age, and their corresponding list of values.

import pandas as pd
import numpy as np

name_age = {'Name' : ['Ali', 'Bill', 'David', 'Hany', 'Ibtisam'],
'Age' : [32, 55, 20, 43, 30]}
data_frame = pd.DataFrame(name_age)
print data_frame

If you run the above script, you should get an output similar to the following:

pandas DataFrame

Notice that the DataFrame constructor orders the columns alphabetically. If you want to change the order of the columns, you can type the following under data_frame above:

data_frame_2 = pd.DataFrame(name_age, columns = ['Name', 'Age'])

To view the result, simply type: print data_frame_2.

Say you didn't want to use the default labels 0,1,2,..., and wanted to use a, b, c,... instead. In that case, you can use index in the above script as follows:

data_frame_2 = pd.DataFrame(name_age, columns = ['Name', 'Age'], index = ['a', 'b', 'c', 'd', 'e'])

That was very nice, wasn't it? Using DataFrame, we were able to see our data organized in a tabular form.

Series

Series is the second pandas data structure I'm going to talk about. A Series is a one-dimensional (1D) object similar to a column in the table. If we want to create a Series for a list of names, we can do the following:

series = pd.Series(['Ali', 'Bill', 'David', 'Hany', 'Ibtisam'],
index = [1, 2, 3, 4, 5])
print series

The output of this script would be as follows:

Series output

Notice that we used index to label the data. Otherwise, the default labels will start from 0,1,2...

Pandas Functions 

In this section, I'm going to show you examples of some functions we can use with DataFrame and Series.

Head and Tail

The functions head() and tail() enable us to view a sample of our data, especially when we have a large number of entries. The default number of elements that get displayed are 5, but you can return the customized number you like.

Let's say we have a Series composed of 20,000 random items (numbers):

import pandas as pd
import numpy as np
series = pd.Series(np.random.randn(20000))

Using the head() and tail() methods to observe the first and last five items, respectively, we can do the following:

print series.head()
print series.tail()

The output of this script should be something similar to the following (notice that you might have different values since we are generating random values):

pandas head and tail functions

Add

Let's take an example of the add() function, where we will attempt to add two data frames as follows:

import pandas as pd

dictionary_1 = {'A' : [5, 8, 10, 3, 9],
'B' : [6, 1, 4, 8, 7]}
dictionary_2 = {'A' : [4, 3, 7, 6, 1],
'B' : [9, 10, 10, 1, 2]}
data_frame_1 = pd.DataFrame(dictionary_1)
data_frame_2 = pd.DataFrame(dictionary_2)
data_frame_3 = data_frame_1.add(data_frame_2)
print data_frame_1
print data_frame_2
print data_frame_3

The output of the above script is:

pandas add function

You can also perform this addition process by simply using the + operator: data_frame_3 = data_frame_1 + data_frame_2.

Describe

A very nice pandas function is describe(), which generates various summary statistics for our data. For the example in the last section, let's do the following:

print data_frame_3.describe()

The output of this operation will be:

pandas describe function

Further Resources

This was just a scratch of the surface on Python's pandas. For more details, you can check the pandas documentation, and you can also check some books like Learning Pandas and Mastering Pandas

Conclusion

Scientists sometimes need to carry out some statistical operations and display some neat graphs that require them to use a programming language. But, at the same time, they don't want to spend too much time or be faced with a serious learning curve in carrying out such tasks. 

As we saw in this tutorial, pandas enabled us to represent data in tabular form and carry out some operations on those tables in a very simple way. Combining pandas with other Python libraries, scientists can even do more advanced tasks such as drawing specialized graphs for their data. 

Thus, pandas is a very helpful library and starting point for scientists, economists, statisticians, and anyone willing to perform some data analysis tasks. 

20 Nov 04:30

Последний осенний день в Центральном парке

Теплые деньки кончились и в Нью-Йорке наконец наступила поздняя осень. Это когда ледяной ветер с океана, яркое солнце и опавшие листья под ногами. Всю мою жизнь это время года наступало еще в сентябре. Становилось холодно, промозгло и серо. А тут уже средина ноября, но Центральный парк все так же прекрасен. На каких-то деревьях даже листья еще не пожелтели. У Нью-Йорка много недостатков, но почти все их можно простить за длинную,мягкую и очень красивую осень. Сегодня в Центральном парке было так хорошо, что не хотелось уходить. Жалко только, что дни уже коротки и солнце садится рано. Этот пост посвящен исключительно созерцанию осени в Нью-Йорке.

IMG_8015 copy

2.
IMG_7622

3.
samsebeskazal.livejournal.com-09750.jpg

4. Велосипедисты.
samsebeskazal.livejournal.com-09755.jpg

5.
IMG_7420

6. Бегуны.
samsebeskazal.livejournal.com-09769.jpg

7. Тоже бугун. Но очень медленный.
samsebeskazal.livejournal.com-09762.jpg

8. Резервуар Жаклин Кеннеди.
samsebeskazal.livejournal.com-09764.jpg

9. Башни жилого дома Эльдорадо.
samsebeskazal.livejournal.com-09772.jpg

10.
samsebeskazal.livejournal.com-09775.jpg

11. Это листья. Листья, которые убирают с газонов.
samsebeskazal.livejournal.com-09778.jpg

12.
samsebeskazal.livejournal.com-09784.jpg

13.
samsebeskazal.livejournal.com-09791.jpg

14. Работник парковой службы.
samsebeskazal.livejournal.com-09802.jpg

15. Копы.
samsebeskazal.livejournal.com-09805.jpg

16.
samsebeskazal.livejournal.com-09812.jpg

17.
IMG_7432 copy

18.
samsebeskazal.livejournal.com-09826.jpg

19. Строющийся небоскреб "432 Парк-авеню".
samsebeskazal.livejournal.com-09844.jpg

20.
samsebeskazal.livejournal.com-09846.jpg

21.
DSC05409

22.
samsebeskazal.livejournal.com-09849.jpg

23.
samsebeskazal.livejournal.com-09851.jpg

24.
samsebeskazal.livejournal.com-09859.jpg

25.
DSC06151

26.
DSC06170

27.
samsebeskazal.livejournal.com-09892.jpg

28.
DSC06180

29.
IMG_7433

30.
samsebeskazal.livejournal.com-09912.jpg

31.
samsebeskazal.livejournal.com-09914.jpg

32.
IMG_7600 copy

33.
samsebeskazal.livejournal.com-09938.jpg

34. Белочка.
samsebeskazal.livejournal.com-09953.jpg

35. Белки приходят по первому зову. Вы же знаете, как подзывать белок?
samsebeskazal.livejournal.com-09956.jpg

36.
samsebeskazal.livejournal.com-09958.jpg

37. Две утки.
samsebeskazal.livejournal.com-09967.jpg

38. Лодки.
IMG_7542 copy

39. Музыканты Tribal Baroque. Очень интересный стиль.
samsebeskazal.livejournal.com-09984.jpg

40.
samsebeskazal.livejournal.com-09989.jpg

41.
samsebeskazal.livejournal.com-09999.jpg

42.
samsebeskazal.livejournal.com-00002.jpg

43.
IMG_8338

44. Музыкант.
samsebeskazal.livejournal.com-00004.jpg

45.
IMG_7437 copy

46.
samsebeskazal.livejournal.com-00008.jpg

47. Последний луч солнца.
samsebeskazal.livejournal.com-00010.jpg

48. Спит.
samsebeskazal.livejournal.com-00024.jpg

49.
samsebeskazal.livejournal.com-00035.jpg

50.
samsebeskazal.livejournal.com-00059.jpg

51. Каток.
samsebeskazal.livejournal.com-00042.jpg

52. Дрозды.
samsebeskazal.livejournal.com-00045.jpg

53.
samsebeskazal.livejournal.com-00074.jpg

Фото мои и Владимира Бадикова.


24 Mar 02:21

Multitail

Multitail:

MultiTail allows you to monitor logfiles and command output in multiple windows in a terminal, colorize, filter and merge.

16 Mar 03:21

Avoid These Seven Mistakes to Be a Better Investor

by Kristin Wong

Avoid These Seven Mistakes to Be a Better Investor

Many people fear investing because they're afraid of doing it wrong. It's a valid concern. With investing, mistakes can be devastating. Forbes has put together a list of "the seven deadly investor sins" that you should avoid.

Read more...

14 Mar 23:07

Home Electrical Projects You Can Totally Handle Yourself

by Walter Glenn

Tackling electrical projects around the house can sound daunting if you’ve never tackled one before. But just because the job involves some wires, that doesn’t mean you need to call in the pros. Here are eight common electrical repairs and replacements that you can totally do yourself. No prior experience necessary.

Read more...

28 Feb 02:34

Редчайшие кадры со съемочных площадок любимых советских фильмов


Подборка редких фотографии, позволяющая нам заглянуть за кулисы гениальных и легендарных фильмов Советского Союза, которые навсегда остались в наших сердцах


ссср, фильм, съемки

ссср, фильм, съемки


“Подкидыш”

  • ссср, фильм, съемки

    «Карнавальная ночь»

  • “Верные друзья”

    ссср, фильм, съемки

  • “Девушка без адреса”

    ссср, фильм, съемки

  • “Летят журавли”

    ссср, фильм, съемки

  • “Я иду шагаю по Москве”

    ссср, фильм, съемки

    ссср, фильм, съемки

  • ”Собачье сердце”

    ссср, фильм, съемки

    ссср, фильм, съемки

  • “Покровские ворота”

    ссср, фильм, съемки

    ссср, фильм, съемки

  • ”Солярис”

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

  • “Андрей Рублёв”

    ссср, фильм, съемки

    ссср, фильм, съемки

  • “Вечный зов”

    ссср, фильм, съемки


  • “Вокзал для двоих”

    ссср, фильм, съемки

    ссср, фильм, съемки

  • “Три мушкетера”

    ссср, фильм, съемки

  • “Вий”

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

  • «Берегись автомобиля»

    ссср, фильм, съемки

  • “Зимний вечер в Гаграх”.

    ссср, фильм, съемки

  • “Слуга”

    ссср, фильм, съемки

  • “Неоконченная пьеса о механическом пианино”

    ссср, фильм, съемки

  • “12 стульев”

    ссср, фильм, съемки

  • “Иван Васильевич меняет профессию”

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

  • “Они сражались за родину”

    ссср, фильм, съемки

    ссср, фильм, съемки

  • “Белорусский вокзал”

    ссср, фильм, съемки

  • “Дворянское гнездо”

    ссср, фильм, съемки

  • “Очи чёрные”

    ссср, фильм, съемки

    ссср, фильм, съемки

  • “Место встречи изменить нельзя”

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

  • “Мой ласковый и нежный зверь”

    ссср, фильм, съемки

  • “Кин-дза-дза”

    ссср, фильм, съемки

  • “Гори гори моя звезда”

    ссср, фильм, съемки

  • “Раба любви”

    ссср, фильм, съемки

  • “Торпедоносцы”

    ссср, фильм, съемки

  • “Родня”

    ссср, фильм, съемки

    ссср, фильм, съемки

  • Съёмочная группа фильма “Родня”

    ссср, фильм, съемки

  • “Жестокий романс”

    ссср, фильм, съемки

  • “Бриллиантовая рука”

    ссср, фильм, съемки

  • “Двадцать дней без войны”

    ссср, фильм, съемки

  • “О бедном гусаре замолвите слово”

    ссср, фильм, съемки

  • “Бриллиантовая рука”

    ссср, фильм, съемки

  • “Несколько дней из жизни Обломова”. Артист Ю. Богатырёв и режиссёр Н.Михалков

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

  • “Гараж”

    ссср, фильм, съемки

    ссср, фильм, съемки

    ссср, фильм, съемки

  • “Служебный роман”

    ссср, фильм, съемки

  • “Тихий дон”

    ссср, фильм, съемки

  • С.Эйзенштейн на съёмках фильма “Октябрь”

    ссср, фильм, съемки

  • Съёмочная группа фильма “Зигзаг удачи”

    ссср, фильм, съемки

  • Режиссер Игорь Масленников и съемочная группа фильма «Шерлок Холмс: ХХ век начинается»

    ссср, фильм, съемки