Как импортировать CSV в отдельные переменные для «подсчета» для гистограммы Matplotlib - PullRequest
0 голосов
/ 03 июня 2018

Я сейчас программирую некоторую описательную аналитику для файла CSV.

Что я хочу сделать; Создать гистограмму вхождения Местоположения в файле CSV и построить график на гистограмме.

Мне интересно, есть ли способ импортировать «много» разных мест в виде отдельных переменных, как янеобходимо добавить 1 к каждой переменной, когда регулярное выражение сопоставляется с CSV.

Вызывается столбец CSV;(Некоторые сокращенно обозначаются как переменные)

Город:

COL = 0
Barnet = 0
Bexley = 0
BAD = 0
Brent = 0
Bromley = 0
Camden = 0
Croydon = 0
Ealing = 0
Enfield = 0
Greenwich = 0
Hackney = 0
HAF = 0
Haringey = 0
Harrow = 0
Havering = 0
Hillingdon = 0
Hounslow = 0
Islington = 0
KAC = 0
KUT = 0
Lambeth = 0
Lewisham = 0
Merton = 0
Newham = 0
Redbridge = 0
RUT = 0
Southwark = 0
Sutton = 0
TowerHamlets = 0
WalthamForest = 0
Wandsworth = 0
Westminster = 0
OuterBorough = 0
InnerBorough = 0*

Вот мой текущий код с выводом изображения ниже:

#Start of Imports 
import csv 
import sys 
import numpy as np 
import pandas as pd 
import re 
import matplotlib.pyplot as plt 
#End of Imports

#Start of Declarations 
COL = 0
Barnet = 0
Bexley = 0
BAD = 0
Brent = 0
Bromley = 0
Camden = 0
Croydon = 0
Ealing = 0
#This is as far as I got when I thought something was wrong?
Enfield = 0
Greenwich = 0
Hackney = 0
HAF = 0
Haringey = 0
Harrow = 0
Havering = 0
Hillingdon = 0
Hounslow = 0
Islington = 0
KAC = 0
KUT = 0
Lambeth = 0
Lewisham = 0
Merton = 0
Newham = 0
Redbridge = 0
RUT = 0
Southwark = 0
Sutton = 0
TowerHamlets = 0
WalthamForest = 0
Wandsworth = 0
Westminster = 0
OuterBorough = 0
InnerBorough = 0
#End of Declarations

#Starts reading 'csv file'  
csv = pd.read_csv ('land-area-population-density-london.csv') #Not sure what this does, index_col=3)

#Start of IF Statement  
csva = np.array(csv) 
for column in np.arange(0, csva.shape[0]): 
    if re.match(r"Barnet", str(csva[column][2])) is not None:         
        Barnet = Barnet + 1
    elif re.match(r"Bexley", str(csva[column][2])) is not None:         
        Bexley = Bexley + 1
    elif re.match(r"City of London", str(csva[column][2])) is not None:         
        COL = COL + 1
    elif re.match(r"Barking and Dagenham", str(csva[column][2])) is not None:         
        BAD = BAD + 1
    elif re.match(r"Brent", str(csva[column][2])) is not None:         
        Brent = Brent + 1
    elif re.match(r"Bromley", str(csva[column][2])) is not None:         
        Bromley = Bromley + 1
    elif re.match(r"Camden", str(csva[column][2])) is not None:         
        Camden = Camden + 1
    elif re.match(r"Croydon", str(csva[column][2])) is not None:         
        Croydon = Croydon + 1
    elif re.match(r"Ealing", str(csva[column][2])) is not None:         
        Ealing = Ealing + 1
#End of IF Statement

#Start of graph fields
#Below: Places is the labels for the placesvar
places = ('Barnet', 'Bexley', 'City of London', 'Barking and Dagenham', 'Brent', 'Bromley', 'Camden', 'Croydon', 'Ealing')
#Below: placesvar the actual 'places' pulled from CSV
placesvar = [Barnet, Bexley, COL, BAD, Brent, Bromley, Camden, Croydon, Ealing]
#Y Positioning numpy.arange (Again no idea what this does) length 'places pulled from csv'
y_pos = np.arange(len(placesvar)) 
#End of graph fields

#Start of Graph positions and Names 
plt.bar(y_pos, placesvar, align='center') 
plt.xticks(y_pos, places, rotation=60) 
plt.ylabel('No. of occurance') 
plt.xlabel('Locations') 
plt.title('Occurance of Locations') 
#plt.savefig('file.png')(Commented out for testing) 
#End of Graph positions and Names
plt.show()

Этовывод моего текущего кода.В этом столбце «Город» отсутствуют некоторые переменные.This is the output of my current code. This is missing a few variables from the column 'Borough'.

Я прошу прощения за любые вопиющие проблемы, я относительно новичок в Python.


Вот вывод для добавления: print(csv.head())

       Codes             ...             Population per hectare 2011
0  E09000001             ...                               23.405268
1  E05000026             ...                               99.968726
2  E05000027             ...                               76.304188
3  E05000028             ...                               89.914330
4  E05000029             ...                               29.647929

[5 rows x 10 columns]

FIG1

1 Ответ

0 голосов
/ 04 июня 2018

Надеюсь, я правильно понял ваш вопрос ...

Это упрощенный пример вашей проблемы (я считаю):

Входные данные test.csv:

    Codes   Borough
0   E1  A
1   E2  B
2   E1  A
3   E1  A
4   E3  C
5   E2  B
6   E1  A
7   E3  C

Код:

import pandas as pd
import matplotlib.pyplot as plt

# read-in data
data = pd.read_csv('./test.csv', sep='\t') #adjust sep to your needs

# count occurences
occurrences = data.loc[:, 'Borough'].value_counts()

# plot histogram
plt.bar(occurrences.keys(), occurrences)

simple example histogram

Вместо data.loc вы также можете использовать data.iloc[:, 2], чтобы выбрать 3-й столбец вместо столбцапо имени Borough.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...