Поиск по блогу

Показаны сообщения с ярлыком pandas-cookbook. Показать все сообщения
Показаны сообщения с ярлыком pandas-cookbook. Показать все сообщения

среда, 18 марта 2015 г.

9 - Loading data from SQL databases

Kопипаст из pandas-cookbook.To connect to sqlite3, or MySQL, or PostgreSQL database: import sqlite3, MySQLdb, psycopg2 So far we've only talked about reading data from CSV files. That's a pretty common way to store data, but there are many others! Pandas can read from HTML, JSON, SQL, Excel (!!!), HDF5, Stata, and a few other things. In this chapter we'll talk about reading data from SQL databases.

You can read data from a SQL database using the pd.read_sql function. read_sql will automatically convert SQL column names to DataFrame column names.

read_sql takes 2 arguments: a SELECT statement, and a database connection object. This is great because it means you can read from any kind of SQL database -- it doesn't matter if it's MySQL, SQLite, PostgreSQL, or something else. This example reads from a SQLite database, but any other database would work the same way.

8.1 Parsing Unix timestamps (atime = 1387295797 ctime=1367633260)

Kопипаст из pandas-cookbook. Секунды эпохи переводятся сначала popcon['atime'].astype(int), а потом преобразуем целые в datetime pd.to_datetime(popcon['atime'], unit='s')
It's not obvious how to deal with Unix timestamps in pandas -- it took me quite a while to figure this out. The file we're using here is a popularity-contest file I found on my system at /var/log/popularity-contest. Here's an explanation of how this file works. I'm going to hope that nothing in it is sensitive :)

вторник, 17 марта 2015 г.

7 - Cleaning up messy data (сортировка и фильтрация в строках Zip кодов)

Kопипаст из pandas-cookbook. Чтобы найти "мусор" сначала используем .unique(), для числовых данных можно строить гистограммы. В сводной таблице NYC обращений в службу 311 данные об инцендентах во всех штатах.
Главное, решить, что делать - убирать или изменять (пропущенные данные, дефисы, длинные строки...). Вот пример чистки по содержанию столбца requests['Incident Zip'].str.contains('-').fillna(False), .sort('Incident Zip'), zips.str.startswith('0') | zips.str.startswith('1'), zips.notnull()
One of the main problems with messy data is: how do you know if it's messy or not? We're going to use the NYC 311 service request dataset again here, since it's big and a bit unwieldy.

6 - String Operations- Which month was the snowiest (снег и температура в 2012 году)

Kопипаст из pandas-cookbook. Таблица погоды за 2012 год из предыдущей (пятой), фильтруем по слову в столбце contains('Snow'), строим димграмму снегопадов за год, затем при помощи resample() находим сренемесячные медианы температуры и объединяем в красивые диаграммы снегопады и температутру.
You'll see that the 'Weather' column has a text description of the weather that was going on each hour. We'll assume it's snowing if the text description contains "Snow"... pandas provides vectorized string functions, to make it easy to operate on columns containing text. There are some great examples in the documentation.

понедельник, 16 марта 2015 г.

5 - Combining dataframes and scraping Canadian weather data

Kопипаст из pandas-cookbook. Исследуем погоду в Канаде, дабы потом определить, процент велосипедистов-маньяков, катающихся в дождь. Из таблицы 2012 года вырезаем март, строим график температуры, потом строим таблицу марта с несколькорми прарматрами (влажность, ветер...). Потом убираем оттуда лишние столбцы (день, месяц..., поскольку есть столбец в формате даты). Строим осредненную (за март) дневную диаграмму температуры по часам... Потом собираем все данные за год concat(data_by_month)

By the end of this chapter, we're going to have downloaded all of Canada's weather data for 2012, and saved it to a CSV. We'll do this by downloading it one month at a time, and then combining all the months together. Here's the temperature every hour for 2012!

4.1 Adding a 'weekday' column to our dataframe (Monthreal Berry bikepath table)

Продолжаем копипаст из pandas-cookbook. Возвращаемся к исследованию велодомаршрута на улице Berri. Здесь за день проезжает несколько тысяч велосипедистов. Сгруппируем их по дняям недели weekday_counts, aggregate(sum)
Okay! We're going back to our bike path dataset here. I live in Montreal, and I was curious about whether we're more of a commuter city or a biking-for-fun city -- do people bike more on weekends, or on weekdays?

3.1 Selecting only noise complaints (самый шумный - Манхеттен)

Продолжаем копипаст из pandas-cookbook. Фильтруем шум на тротуарах сначала в Бруклине, а потом во всех районах. Отвлекаемся на то чтобы получить NumPy array...
I'd like to know which borough has the most noise complaints. First, we'll take a look at the data to see what it looks like... huge ugly table :)

2 - Selecting data & finding the most common complaint type (Жалобы NYC Open Data)

Продолжаем копипаст из pandas-cookbook. На что большее всего жалуются в разных районах Нью-Йорка. Используем .value_counts()
We're going to use a new dataset here, to demonstrate how to deal with larger datasets. This is a subset of the of 311 service requests from NYC Open Data.

воскресенье, 15 марта 2015 г.

1.1 Reading data from a csv file (Пример с велосипедистами в Монреале)

Это копипаст из pandas-cookbook, поскольку мне категорически не понравилось форматирование на nbViewer.
You can read data from a CSV file using the read_csv function. By default, it assumes that the fields are comma-separated.
We're going to be looking some cyclist data from Montréal. Here's the original page (in French), but it's already included in this repository.
We're using the data from 2012. This dataset is a list of how many people were on 7 different bike paths in Montreal, each day.

0. Введение к Pandas-cookbook: A quick tour of IPython Notebook (копипаст)

Здесь и далее копипаст 10-ти постов из репозитория Pandas-cookbook. Сначала я ничего не запомнил после чтения оригинала в NbViewer... там был авторский изыск с плохим форматированием (часть строк была просто скрыта), потом я не смог найти более полезной подборки примеров. Потом я понял, что здесь собраны как раз такие профессиональные приемы, которые я просто обязан запомнить, как "Отче наш..." Так что далее будут посты, начинающиеся с цифр, это и есть копипаст из Pandas-cookbook