Пример #1
0
        p = 0.017453292519943295
        a = 0.5 - cos(
            (lat2 - lat1) * p) / 2 + cos(lat1 * p) * cos(lat2 * p) * (1 - cos(
                (lon2 - lon1) * p)) / 2
        return 12742 * asin(sqrt(a))

    def closest(data, v):
        return min(
            data,
            key=lambda p: distance(v['lat'], v['lon'], p['lat'], p['lon']))

    v = {'lat': float(lat_ad), 'lon': float(lon_ad)}
    check_des = v
    tmp = [{'lat': df['lat'][i], 'lon': df['lon'][i]} for i in range(len(df))]
    df_end = df[(df.lat == (closest(tmp, v)['lat']))
                & (df.lon == closest(tmp, v)['lon'])]
    address = g.city
    check_des = address

else:
    city_now = st.selectbox('You are in ', df.city.unique())
    dis_now = st.selectbox('', df.dis.unique())
    df_end = df[(df.city == city_now) & (df.dis == dis_now)]
    check_des = [df_end.city, df_end.dis]

st.write('Safe places near you', df_end)
st.map(df_end)

st.write('Need help? Contact for ____')
st.write('Safety steps: ')
Пример #2
0
                     color='Tweets')
        st.plotly_chart(fig)
    else:
        fig = px.pie(sentiment_count, values='Tweets', names='Sentiment')
        st.plotly_chart(fig)

        #map
st.sidebar.subheader("Hour of Tweet")
hour = st.sidebar.slider("Hour of day", 0, 23)
#number = st.sidebar.number_input("Number input",min_value=101,max_value=1001)
modified_data = data[data['tweet_created'].dt.hour == hour]
if not st.sidebar.checkbox("Close", False, key='1'):
    st.markdown("Tweets location based on hour of day")
    st.markdown('### %i tweets between %i:00 hours and %i:00' %
                (len(modified_data), hour, (hour + 1) % 24))
    st.map(modified_data)
    if st.sidebar.checkbox("Show raw data", False):
        st.write(modified_data)

st.sidebar.subheader("Sentiments by airlines")
choice = st.sidebar.multiselect('Pick airlines',
                                ('Virgin America', 'United', 'Southwest',
                                 'Delta', 'US Airways', 'American'))

if len(choice) > 0:
    choice_data = data[data.airline.isin(choice)]
    fig_choice = px.histogram(choice_data,
                              x='airline',
                              y='airline_sentiment',
                              histfunc='count',
                              color='airline_sentiment',
DATE_COLUMN = 'date/time'
DATA_URL = ('https://s3-us-west-2.amazonaws.com/'
            'streamlit-demo-data/uber-raw-data-sep14.csv.gz')

@st.cache
def load_data(nrows):
    data = pd.read_csv(DATA_URL, nrows=nrows)
    lowercase = lambda x: str(x).lower()
    data.rename(lowercase, axis='columns', inplace=True)
    data[DATE_COLUMN] = pd.to_datetime(data[DATE_COLUMN])
    return data

data_load_state = st.text('Loading data...')
data = load_data(10000)
data_load_state.text('Loading data... done!')

if st.checkbox('Show raw data'):
    st.subheader('Raw data')
    st.write(data)

st.subheader('Number of pickups by hour')
hist_values = np.histogram(data[DATE_COLUMN].dt.hour, bins=24, range=(0,24))[0]
st.bar_chart(hist_values)

# Some number in the range 0-23
hour_to_filter = st.slider('hour', 0, 23, 17)
filtered_data = data[data[DATE_COLUMN].dt.hour == hour_to_filter]

st.subheader('Map of all pickups at %s:00' % hour_to_filter)
st.map(filtered_data)
Пример #4
0
        with open(feature_imp, mode="r") as file:
            final_features_list = file.read().replace('"',"")\
                                             .replace("'","")\
                                                .replace("[","")\
                                                .replace("]","")\
                                            .split(",")

        st.pyplot(fig1)
        fig2, ax = plt.subplots()
        if feature == 1:
            feat_importances = pd.Series(
                model.steps[1][1].feature_importances_,
                index=final_features_list)
            feat_importances.nlargest(n=20).sort_values(ascending=True).plot(
                kind='barh', color='Orange', width=0.3, figsize=(15, 7))
            plt.xlabel('Relative Feature Importance')

            st.pyplot(fig2)

        st.write('Predicción')
        st.map(results[results['Accident_Severity_predicted'] == 0][[
            'lat', 'lon'
        ]])
        st.write('Valor real')
        st.map(results[results['Accident_Severity'] == 0][['lat', 'lon']])

        #st.dataframe(results['Accident_Severity_predicted'].head(20))
        #st.dataframe(results.head(10))
    else:
        pass
Пример #5
0
st.write(df)

checkbox = st.checkbox('Show line chart', value=False)
print(checkbox)
if checkbox:
    chart_data = pd.DataFrame(np.random.randn(20, 3), columns=['a', 'b', 'c'])

    st.dataframe(chart_data)
    st.line_chart(chart_data)

map_data = pd.DataFrame(np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
                        columns=['lat', 'lon'])

st.dataframe(map_data)
st.map(map_data)

option = st.sidebar.selectbox('Which number do you like best?',
                              df['first column'])

'You selected:', option

'Starting a long computation...'

# Add a placeholder
latest_iteration = st.empty()
bar = st.progress(0)

for i in range(100):
    # Update the progress bar with each iteration.
    latest_iteration.text(f'Iteration {i+1}')
Пример #6
0
    relevant_sensors = get_relevant_sensors(all_useful_sensors_df, lat, lon,
                                            radius)
    SENSORS = relevant_sensors.to_dict("records")

# MAIN

if lat and lon:
    st.title("AQI for Coordinates (%f, %i)" % (lat, lon))
elif address:
    st.title("AQI for %s)" % address)
else:
    st.title("Enter a location to load sensor grid")
#st.write("<hr />", unsafe_allow_html=True)

with st.beta_expander(label="Map of Nearby Sensors"):
    st.map(relevant_sensors)

# set up the layout grid
COLUMNS = st.beta_columns(circles_per_row)

# SENSOR GRID

container_x = 0
for idx in range(len(SENSORS)):
    sensor = SENSORS[idx]

    with COLUMNS[container_x]:
        st.write(sensor_div(sensor['usaqi']), unsafe_allow_html=True)
        st.write(sensor["name"])
        st.write("{:.2f} km".format(sensor["dist"]))
Пример #7
0
showdata = st.sidebar.checkbox('Show Line graph timeseries data')
if showdata == True:
    st.dataframe(plotdata)
else:
    st.write()

###Plot a streamlit map
st.header('Explore the infection spreading with a map')
df2 = getmedata()[1]
df2.rename(columns={
    'Lat': 'lat',
    'Long': 'lon',
    'Province/State': 'Province',
    'Country/Region': 'Country'
},
           inplace=True)
maxslide = len(df2.columns) - 5
slide = st.slider('Slide across to explore infection spread', 0, maxslide, 10)
datecolumn = df2.columns[slide + 4]
datecolumnlist = [datecolumn]
st.subheader('Infections Recorded on ' + datecolumn)
dfmap = df2[['Country', 'Province', 'lat', 'lon', datecolumn]]
dfmap = dfmap.replace(0, np.nan).dropna(subset=[datecolumn, 'lat', 'lon'])
st.map(dfmap[['lat', 'lon']])
mapgraph = st.sidebar.checkbox('Show map data')

if mapgraph == True:
    st.dataframe(dfmap)
    st.write()
else:
    st.write()
Пример #8
0
                                  title='Countries with Recovered Cases')
            st.plotly_chart(fig_2)

    st.header("Which data you want to visulize")
    select = st.selectbox('Affected class', [
        'Confirm Cases of COVID-19', 'Death by COVID-19',
        'Recovery by COVID-19'
    ])

    if select == 'Confirm Cases of COVID-19':
        st.header("Where are the most Cases occured in the world?")
        confirm_max = np.max(data['confirmed'])
        dead_people = st.slider("Number of Cases by COVID-19 virus", 0,
                                int(confirm_max))
        st.map(
            data.query("confirmed >= @dead_people")[["lat",
                                                     "lon"]].dropna(how="any"))
        #st.write(original_data.query("injured_pedestrians >= 1")[["on_street_name", "injured_pedestrians"]].sort_values(by=['injured_pedestrians'], ascending=False).dropna(how="any")[:5])

    elif select == 'Death by COVID-19':
        st.header("Where are the most Death occure in the world?")
        dead_max = np.max(data['deaths'])
        dead_people = st.slider("Number of Death by COVID-19 virus", 0,
                                int(dead_max))
        st.map(
            data.query("deaths >= @dead_people")[["lat",
                                                  "lon"]].dropna(how="any"))
        #st.write(original_data.query("injured_cyclists >= 1")[["on_street_name", "injured_cyclists"]].sort_values(by=['injured_cyclists'], ascending=False).dropna(how="any")[:5])

    else:
        st.header("Where are the most Recovery occure in the world?")
Пример #9
0
def main():
    st.title("Exploratory Data Analysis on ACT Scores")
    st.sidebar.title("EDA on ACT Scores")
    st.sidebar.subheader("By [Meral Balik](https://github.com/Meralbalik)")
    st.sidebar.markdown(
        "[![View on GitHub](https://img.shields.io/badge/GitHub-View_on_GitHub-blue?logo=GitHub)](https://github.com/Meralbalik/ACTstreamlit)"
    )
    st.markdown(
        "This application is a Streamlit dashboard that visualizes exploratory analysis on ACT scores of high schools in CA. The ACT test is designed to assess high school students' general educational development and their ability to complete college-level work. ACT test covers four subject areas: English, mathematics, reading, and science. Each subject area test receives a score ranging from 1 to 36. "
    )
    st.sidebar.markdown(
        "This application is a Streamlit dashboard that visualizes exploratory analysis on ACT scores of high schools in CA."
    )

    @st.cache(persist=True)
    def load_data():
        data = pd.read_csv('data.csv')
        data.rename(
            {
                'Dname': 'District',
                'Cname': 'County',
                'Lat': 'lat',
                'Lon': 'lon'
            },
            axis=1,
            inplace=True)
        data['AvgScr'] = data.loc[:, 'AvgScrEng':'AvgScrSci'].mean(axis=1)
        return data

    data = load_data()

    if st.sidebar.checkbox("Show Raw Data", False):
        st.sidebar.text('Showing the first 10 rows of the data.')
        st.subheader('Raw Data')
        st.write(data.head(10))
    #------------------------------------------------------------------------------------------------------------------

    # Histogram of the scores
    st.subheader("Distribution of the Scores in Five Years")
    st.text(
        "Select a school year and a test subject from the dropdown menu on the left."
    )
    st.sidebar.subheader("Distribution of the Scores in Five Years")
    select = st.sidebar.selectbox(
        "Select a School Year",
        ['2013-14', '2014-15', '2015-16', '2016-17', '2017-18'],
        key="1")
    choice = st.sidebar.selectbox("Visualization Type",
                                  ['Histogram', 'Pie Chart'],
                                  key="2")
    filtered = data[['Year', 'Sname', 'AvgScr']]

    # Histogram
    def histogram(year):
        hist = np.histogram(filtered[filtered.Year == year]['AvgScr'],
                            bins=36,
                            range=(0, 36))[0]
        chart_data = pd.DataFrame({
            'scores': range(0, 36),
            'number of schools': hist
        })
        fig = px.bar(chart_data,
                     x='scores',
                     y='number of schools',
                     hover_data=['scores', 'number of schools'],
                     height=400,
                     width=780)
        return st.write(fig)

    def piechart(year):
        df = filtered[filtered.Year == year]
        percentiles = np.array([0, 2.5, 25, 50, 75, 97.5, 100])
        perct = np.percentile(df['AvgScr'], percentiles)
        labels = {
            i: f'{percentiles[i]}% to {percentiles[i+1]}%'
            for i in range(0, 6)
        }
        score_range = {i: f'{perct[i]} to {perct[i+1]}' for i in range(0, 6)}
        df['Bin'] = pd.cut(df['AvgScr'], perct, labels=False)
        a = df.groupby('Bin')['Sname'].count()
        a = pd.DataFrame({
            "Score Range": a.index,
            "# of Schools": a.values.flatten()
        })
        a['Score Range'] = a["Score Range"].map(score_range)
        fig = px.pie(a,
                     values="# of Schools",
                     names="Score Range",
                     height=400,
                     width=800)
        return st.write(fig)

    def select_year(function):
        if select == '2013-14':
            function(2014)
        if select == '2014-15':
            function(2015)
        if select == '2015-16':
            function(2016)
        if select == '2016-17':
            function(2017)
        if select == '2017-18':
            function(2018)

    if choice == 'Pie Chart':
        select_year(piechart)

    if choice == 'Histogram':
        select_year(histogram)

    #------------------------------------------------------------------------------------------------------------------

    # Breakdown scores by subject
    st.subheader("Breakdown Scores by Subject")
    st.text(
        "Select a school year and a test subject from the dropdown menu on the left."
    )
    st.sidebar.subheader("Breakdown Scores by Subject")
    select = st.sidebar.selectbox(
        "Select a School Year",
        ['2013-14', '2014-15', '2015-16', '2016-17', '2017-18'],
        key="3")
    filtered = data[[
        'Year', 'AvgScrEng', 'AvgScrRead', 'AvgScrMath', 'AvgScrSci'
    ]]
    subject = ['AvgScrEng', 'AvgScrRead', 'AvgScrMath', 'AvgScrSci']
    choice = st.sidebar.multiselect("Pick Subject(s)",
                                    subject,
                                    default=["AvgScrEng"])

    def subjects(year):
        df = filtered[filtered.Year == year]
        df = df[['AvgScrEng', 'AvgScrRead', 'AvgScrMath', 'AvgScrSci']]
        if len(choice) > 0:
            chosen_data = df[choice]
            fig = px.histogram(chosen_data, height=400, width=800)
            st.write(fig)

    select_year(subjects)

    #--------------------------------------------------------------------------------------------
    # Map
    st.subheader("Where are the schools located based on their scores?")
    st.text("Select a score range from the slider on the left.")
    st.sidebar.subheader(
        "Where are the schools located based on their scores?")
    scores = st.sidebar.slider("Select a score range",
                               14,
                               31, [20, 25],
                               key='1')
    st.write(
        f"Showing the average ACT scores in the range {scores[0], scores[1]}.")
    map_data = data.groupby('gsId')['AvgScr'].mean().reset_index()
    map_data = map_data.merge(data[['gsId', 'lat', 'lon']],
                              on='gsId',
                              how='left').drop_duplicates()
    st.map(
        map_data.query("@scores[0] <= AvgScr <= @scores[1]")[[
            'lat', 'lon'
        ]].dropna(how="any"))

    #------------------------------------------------------------------------------------------------------------------
    # 3D Map
    st.subheader("Number of schools at each location?")
    st.text("Select a score range from the slider on the left.")
    st.sidebar.subheader("Number of schools at each location?")
    scores = st.sidebar.slider("Select a score range",
                               14,
                               31, [20, 25],
                               key='2')
    st.write(
        f"Showing the average ACT scores in the range {scores[0], scores[1]}.")
    new_data = map_data[(map_data.AvgScr >= scores[0])
                        & (map_data.AvgScr <= scores[1])]
    new_data = new_data[['lat', 'lon']]

    layer = pdk.Layer(
        "HexagonLayer",
        new_data,
        get_position="[lon, lat]",
        auto_highlight=True,
        elevation_scale=50,
        radius=3000,
        pickable=True,
        elevation_range=[0, 3000],
        extruded=True,
        coverage=1,
    )

    # Set the viewport location
    view_state = pdk.ViewState(longitude=-119.417931,
                               latitude=36.778259,
                               zoom=5.5,
                               min_zoom=5,
                               max_zoom=15,
                               pitch=40.5,
                               bearing=-27.36)

    # Combined all of it and render a viewport
    map_3d = pdk.Deck(map_style="mapbox://styles/mapbox/light-v9",
                      layers=[layer],
                      initial_view_state=view_state,
                      tooltip={
                          "html": "<b>Elevation Value:</b> {elevationValue}",
                          "style": {
                              "color": "white"
                          }
                      })
    st.write(map_3d)
Пример #10
0
    def test_default_map_copy(self):
        """Test that _DEFAULT_MAP is not modified as other work occurs."""
        self.assertEqual(_DEFAULT_MAP["initialViewState"]["latitude"], 0)

        st.map(df1)
        self.assertEqual(_DEFAULT_MAP["initialViewState"]["latitude"], 0)
Пример #11
0
                        if st.checkbox(
                                "Show Statistical Data Per Chosen Region",
                                False):
                            for i in region_df:
                                st.write('Stats of', i)
                                st.write(region_df[i])
        else:
            result_df = result_df
#########################################################################################################

st.write('### Filter results: ', result_df.shape[0], ' earthquakes detected')
st.write('### From (date): `%s` To (date):`%s`' %
         (result_df['date_time_utc'].dt.date.min(),
          result_df['date_time_utc'].dt.date.max()))
# Map
st.map(result_df)
#Raw data display
if st.checkbox("Show Detailed Data", False):
    st.write(result_df.drop('date_time_utc', axis=1))

#visually dividing section
st.write(
    '___________________________________________________________________________________________________'
)
#footer
st.write(
    '''\n[Check the data cleaning Jupiter Notebook here](https://github.com/beksultankarimov/earthequakes-streamlit/blob/main/Earthquakes_Data_Cleaning_.ipynb)'''
)
st.write(
    '''\n[Check the EDA Jupiter Notebook here](https://github.com/beksultankarimov/earthequakes-streamlit/blob/main/Earthquake_EDA.ipynb)'''
)
Пример #12
0
    def test_no_args(self):
        """Test that it can be called with no args."""
        st.map()

        c = self.get_delta_from_queue().new_element.deck_gl_json_chart
        self.assertEqual(json.loads(c.json), _DEFAULT_MAP)
Пример #13
0
                       parse_dates=[['CRASH DATE', 'CRASH TIME']])
    data.dropna(subset=['LATITUDE', 'LONGITUDE'], inplace=True)
    lowercase = lambda x: str(x).lower()
    data.rename(lowercase, axis='columns', inplace=True)
    data.rename(columns={'crash date_crash time': 'date/time'}, inplace=True)
    return data


original_data = load_data(100000)
data = original_data.copy()

st.header("Where are the most people injured in NYC?")
injured_people = st.slider("Number of persons injured in vehicle collisions",
                           0, 19)
st.map(
    data.query("`number of persons injured` >= @injured_people")[[
        "latitude", "longitude"
    ]].dropna(how="any"))

st.header("How many collisions occur during a given time of the day?")
hour = st.slider("Hour to look at", 0, 23)
data = data[data['date/time'].dt.hour == hour]

st.markdown("Vehicle collisions between %i:00 and %i:00" % (hour,
                                                            (hour + 1) % 24))
midpoint = (np.average(data['latitude']), np.average(data['longitude']))

st.write(
    pdk.Deck(map_style="mapbox://styles/mapbox/light-v9",
             initial_view_state={
                 "latitude": midpoint[0],
                 "longitude": midpoint[1],
Пример #14
0
sub_df = sub_df.groupby('date').agg(sum)
st.line_chart(sub_df["price"])

st.title('使用plotly的api画图')
fig = ff.create_distplot([sub_df['price']],
                         group_labels=['price'],
                         bin_size=2500)
st.plotly_chart(fig, use_container_width=True)

st.title('使用Matplotlib的api画图')
fig, ax = plt.subplots()
ax.hist(df['price'], bins=20)
st.pyplot(fig)

# sidebar插件
product_list = df["product"].unique()

product_type = st.sidebar.selectbox(
    "Which kind of event do you want to explore?", product_list)
country_list = df["country"].unique()

country_name = st.sidebar.selectbox("Which Country do you want to explore?",
                                    country_list)

part_df = df[(df["product"] == product_type) & (df['country'] == country_name)]
st.write(f"根据你的筛选,数据包含{len(part_df)}行")

# map
st.title('地图的使用')
st.map(part_df)
Пример #15
0
import streamlit as st
import pandas as pd

st.header('data hack 2020')


DATA_PREFIX = '../../data/' 
zipcode_to_latlong_path = 'zipcode-to-latlong.csv'

zipcode_to_latlong = pd.read_csv(zipcode_to_latlong_path)

physician_location = pd.read_csv(f'{DATA_PREFIX}hf_physician_locator.csv') 
physician_location = physician_location.assign(PostalCode = physician_location.PostalCode.apply(lambda x: int(x[:5])))
physician_location = physician_location.merge(
        zipcode_to_latlong, how='inner', left_on='PostalCode', right_on='ZIP'
        ).rename(columns={'LAT': 'lat', 'LNG': 'lon'})


st.dataframe(physician_location)

st.map(physician_location[['lat', 'lon']])

st.write(physician_location.dtypes, zoom=13)



Пример #16
0
def draw_map(df):
    st.map(df[["latitude", "longitude"]], zoom=0)
Пример #17
0
import streamlit as st
import pandas as pd

df = pd.read_csv('criminalidade_sp_2.csv')

st.title('Criminalidade em São Paulo')
st.markdown('''
    A **criminalidade** é um problema recorrente no Brasil.
    Buscamos sempre formas de diminuir esses índices e usando técnicas de Ciência de Dados conseguimos entender melhor
    o que está acontecendo e gerar insights que direcionam ações capazes de diminuir índices de criminalidade.
   ''')

st.sidebar.info(f'Foram carregadas {df.shape[0]} linhas.')

if st.sidebar.checkbox('Ver dados de entrada'):
    st.header('Dados de Entrada')
    st.write(df)

df.time = pd.to_datetime(df.time)
ano_selecionado = st.sidebar.slider('Selecione um ano', 2010, 2018, 2015)
df_selected = df[df.time.dt.year == ano_selecionado]

st.subheader('Mapa de Criminalidade')
st.map(df_selected)
import streamlit as st
import pandas as pd
import numpy as np

st.title('California Housing')

@st.cache
def load_data():
    df = pd.read_csv("/Users/yelkhattabi/DSTI_Workshop/datasets/housing.csv")
    df = df.drop(index=df[df.total_bedrooms.isna()].index)
    return df

data_load_state = st.text('Loading data...')
data = load_data()
data_load_state.text("Done! (using st.cache)")

if st.checkbox('Show raw data'):
    st.subheader('Raw data')
    st.write(data)


st.subheader('Map')
st.map(data)
Пример #19
0
                               category_group))
        # Sortowanie i selekcja
        maps.get_best(ans, radius, min_stars, max_cena)
        # Sortowanie według zatłoczenia
        if maps.is_possible_checktime(cfg['private_api_key']):
            today = datetime.date.today().strftime('%A')
            hour = datetime.datetime.now().hour
            maps.check_popularity(cfg['private_api_key'], ans, today, hour)
            maps.sorting_by(ans, 'popularity', 3)
        else:
            st.info("BRAKUJE CREDITÓW W API")
    except maps.NothingFoundError:
        st.text("Aplikacja niestety nie znalazła żadnego miejsca tego typu")
    else:
        # Wyświetlanie
        lat_long = {
            'lat': [i['geometry']['location']['lat'] for i in ans],
            'lon': [i['geometry']['location']['lng'] for i in ans]
        }
        st.map(data=pd.DataFrame.from_dict(lat_long), zoom=14)
        for i in ans:
            st.markdown("  \n ".join((
                f"### {i['name']}", f"**Dystans:** {i['time_text']}",
                f"**Adres:** {i['vicinity']}",
                f"**Zatłoczenie:** *{nazwy_zatloczenie[i.get('popularity', 5)]}*",
                f"**Zakres cenowy:** {get_price(i, '$')}  **Oceny:** {get_price(i, ':star:', type_='rating')}"
            )))
            ph = get_photo(cfg['maps_api_key'], i)
            if not ph is None:
                st.image(ph, width=150)
Пример #20
0
def load_data(nrows):
    data = pd.read_csv(DATA_URL2, nrows = nrows)
    data['Prevalent_Cases'] = data['6/10/20'] - data['5/27/20']
    data.dropna(subset = ["Lat","Long_"], inplace = True)
    data.rename(columns={'Lat':'latitude'}, inplace=True)
    data.rename(columns={'Long_':'longitude'}, inplace=True)
    data = data.iloc[:,6:]
    return data

data = load_data(3261) #Remember to change
original_data = data
#original_data = original_data.rename(columnes = {'6/10/20' : "Total_Cases"})

st.header("Which Areas of the US are at Highest Risk for Corona Virus Cases?")
Number_of_Cases = st.slider("Number of Prevailing Cases",0,10000)
st.map(data.query("Prevalent_Cases >= @Number_of_Cases")[["latitude","longitude"]].dropna(how = "any"))

st.header("How many cases per State/Province?")
state = st.selectbox("State/Province", data['Province_State'].unique())
data = data[data['Province_State'] == state]

st.markdown("Covid-19 Cases in %s" % (state))

midpoint = (np.average(data['latitude']), np.average(data['longitude']))

st.write(pdk.Deck(
    
    map_style= "mapbox://styles/mapbox/light-v9",
    initial_view_state = {
        "latitude": midpoint[0],
        "longitude": midpoint[1],
Пример #21
0
                inplace=True)
    data.rename(columns={'cyclists injured': 'cyclists_injured'}, inplace=True)
    data.rename(columns={'motorists injured': 'motorists_injured'},
                inplace=True)
    data.rename(columns={'on street name': 'on_street_name'}, inplace=True)
    return data


data = load_data(100000)
original_data = data

st.header("Where are the most people injured in NYC?")
injured_people = st.slider("Number of persons injured in vehicle collisions",
                           0, 32)
st.map(
    data.query("persons_injured >= @injured_people")[["latitude", "longitude"
                                                      ]].dropna(how="any"))

st.header("How many collisions occur during a given time of a day?")
hour = st.slider("Hour to look at", 0, 23)
data = data[data["date_time"].dt.hour == hour]

st.markdown("Vehicle collisions between %i:00 and %i:00" % (hour,
                                                            (hour + 1) % 24))

midpoint = (np.average(data['latitude']), np.average(data['longitude']))

st.write(
    pdk.Deck(
        map_style="mapbox://styles/mapbox/light-v9",
        initial_view_state={
Пример #22
0
    # df = df[df.Province_State == 'New York']
    df = df[df.Long_ <= -40]

    # rename for streamlit map to work
    df.rename(columns={'Lat': 'latitude', 'Long_': 'longitude'}, inplace=True)
    confirmed = df[df.Confirmed != 0]
    return df, confirmed


df, confirmed = load_data(NROWS)

st.title("Covid-19 cases in the USA")

# all 2020 confirmed case map
st.header("All confirmed 2020 cases")
st.map(confirmed[["latitude", "longitude"]].dropna(how="any"))
if st.checkbox("Show Data - 162268 confirmed cases", False):
    st.subheader('Data')
    st.write(confirmed)

# confirmed cases for given month
st.header("Cases in a given month")
month = st.slider("Select Month", 1, 5)
st.markdown("Covid-19 cases in 0%i/2020" % month)
data = confirmed[confirmed['Date'].dt.month == month]

midpoint = (np.average(data["latitude"]), np.average(data["longitude"]))
st.write(
    pdk.Deck(
        map_style="mapbox://styles/mapbox/light-v9",
        initial_view_state={
Пример #23
0
                     parse_dates=[['CRASH_DATE', 'CRASH_TIME']])
    df.dropna(subset=['LATITUDE', 'LONGITUDE'], inplace=True)
    lowercase = lambda x: str(x).lower()
    df.rename(lowercase, axis='columns', inplace=True)
    df.rename(columns={'crash_date_crash_time': 'date/time'}, inplace=True)
    return df


df = load_motor_data(100000)
original_data = df

st.header("Where are the most people injured in the New York City:")
injured_people_locations = st.slider(
    "Number of people injured in vehicle collisions", 0, 19)
st.map(
    df.query("injured_persons >= @injured_people_locations")[[
        "latitude", "longitude"
    ]].dropna(how="any"))

st.header("How many collisions occurred during a given time or a day")
hour = st.selectbox("Hour to look at", range(0, 24, 1))
df = df[df['date/time'].dt.hour == hour]

st.markdown("Vehicle collisions between %i:00 and %i:00" % (hour,
                                                            (hour + 1) % 24))
midpoint = (np.average(df['latitude']), np.average(df['longitude']))

st.write(
    pdk.Deck(
        map_style="mapbox://styles/mapbox/light-v9",
        initial_view_state={
            "latitude": midpoint[0],
def demo():
    st.title('Demo 👽')

    st.text(
        'Llena los siguientes datos para darte el precio de la vivienda y el precio/area')

    """
    'area', 'banos', 'estrato', 'garajes', 'habitaciones', 'piso',
    'valoradministracion', 'latitud', 'longitud', '0-1 anos', '1-10 anos',
    '10-30 anos', '30 anos', 'tiponegocio_Arriendo', 'tiponegocio_Venta',
    'tiponegocio_Venta Y Arriendo', 'tipoinmueble_Casa',
    'tipoinmueble_Apartamento'
    """
    col1, col2 = st.beta_columns(2)
    area = col1.number_input(
        '¿Cuál es el área de tu inmueble?', min_value=0, step=1, format='%d')
    banos = col2.number_input(
        '¿Cuántos baños tiene?',
        min_value=0,  step=1, format='%d')
    garajes = col1.number_input(
        '¿Cuántos garajes tiene tu inmueble?', min_value=0,  step=1, format='%d')
    habitaciones = col2.number_input(
        '¿Cuántas habitaciones tiene?', min_value=0,  step=1, format='%d')
    piso = col1.number_input(
        '¿Cuántos pisos tiene tu casa?', min_value=0,  step=1, format='%d')
    estrato = col1.number_input(
        '¿Cual es el estrato? (Valor minimo: 1)', min_value=1,
        step=1, format='%d'
    )
    valoradministracion = col2.number_input(
        '¿Cuánto pagas de administración? (Si no aplica deja en 0)', min_value=0,
        step=1, format='%d'
    )
    valorVivienda = col2.number_input(
        '¿Cuánto crees que cuesta tu casa?', min_value=0,
        step=1, format='%d'
    )

    street = st.text_input("Dirección", "Cra 76 sur # 57-96 ")
    city = st.text_input("Ciudad", "Bogota")
    country = "Colombia"

    location = geoClient.get_cords(f'{street}, {city}, {country}')
    lat = location.lat
    lon = location.lng
    map_data = pd.DataFrame({'lat': [lat], 'lon': [lon]})
    st.map(map_data, zoom=14)
    tiempo_de_construido = st.slider(
        '¿Cuánto años tiene de construido tu inmueble?', min_value=0, max_value=30, value=0, step=1
    )
    tipo_negocio = st.radio('¿Qué tipo de negocio se puede haer con la inmueble?',
                            ('Sólo Venta', 'Arriendo y Venta', 'Sólo Arriendo'))
    tipo_inmueble = st.radio(
        '¿Qué tipo de inmueble es?', ('Casa', 'Apartamento')
    )

    if st.button('Predecir'):
        data = ModelData(
            area=area,
            banos=banos,
            garajes=garajes,
            habitaciones=habitaciones,
            piso=piso,
            estrato=estrato,
            valoradministracion=valoradministracion,
            valorventa=valorVivienda,
            latitud=lat,
            longitud=lon,
        )
        if tipo_inmueble == 'Casa':
            data.tipoinmueble_Casa = 1
        else:
            data.tipoinmueble_Apartamento = 1

        if tiempo_de_construido <= 1:
            data.anos_0_1 = 1
        elif tiempo_de_construido <= 10:
            data.anos_1_10 = 1
        elif tiempo_de_construido <= 30:
            data.anos_10_30 = 1
        else:
            data.anos_30 = 1

        if tipo_negocio == 'Sólo Venta':
            data.tiponegocio_Venta = 1
        elif tipo_negocio == 'Arriendo y Venta':
            data.tiponegocio_Venta_Y_Arri = 1
        else:
            data.tiponegocio_Arriendo = 1
        print(data)
        with st.spinner('Prediciendo...'):
            model = XGBoost()
            model.load_model()
            predictions = model.predict(data.to_arr())

        st.success(f'El precio por metro cuadrado es de: {predictions[0]}')
Пример #25
0
    data.dropna(subset=['LATITUDE', 'LONGITUDE'], inplace=True)
    lowercase = lambda x: str(x).lower()
    data.rename(lowercase, axis='columns', inplace=True)
    data.rename(columns={'crash_date_crash_time': 'date/time'}, inplace=True)
    return data


data = load_data(100000)
original_data = data

st.sidebar.header("Input Parameters")
st.header("Where are the most people injured in NYC ?")
injured_people = st.sidebar.slider(
    "Number of persons injured in vehicle collisions : ", 0, 19)
st.map(
    data.query("injured_persons >= @injured_people")[['latitude', 'longitude'
                                                      ]].dropna(how='any'))

st.header("How many collisions occur during a given time of the day ?")
hour = st.sidebar.number_input("Hour to look at [24 hrs format]",
                               0.0,
                               23.0,
                               step=1.0)
data = data[data['date/time'].dt.hour == hour]

st.markdown("Vehicle collisions between %i:00 and %i:00" % (hour,
                                                            (hour + 1) % 24))
midpoint = (np.average(data['latitude']), np.average(data['longitude']))

st.write(
    pdk.Deck(
        records = cursor.fetchall()
    records = pd.DataFrame(records,
                           columns=[
                               "longitude", "latitude", "restuarantName",
                               "restuarantAddress", "critViolations",
                               "nonCritViolations"
                           ])

    restaurants = st.sidebar.selectbox("Select a restaurant",
                                       (records["restuarantName"]))
    map_plot = records[records.restuarantName == restaurants]
    st.dataframe(map_plot[[
        "restuarantName", "restuarantAddress", "critViolations",
        "nonCritViolations"
    ]].assign(hack='').set_index('hack'))
    st.map(map_plot, zoom=12)

    if st.button("Show COVID data for County"):
        with conn.cursor() as cursor:
            cursor.execute(
                """SELECT updateDate, testsPerformeted, newPostives FROM covid WHERE county = %s ORDER BY updateDate DESC""",
                (county.title(), ))
            records = cursor.fetchall()
        records = pd.DataFrame(
            records, columns=["updateDate", "testsPerformeted", "newPostives"])
        st.line_chart(
            records.rename(columns={
                'updateDate': 'index'
            }).set_index('index'))

    #Show inspections vs covid
Пример #27
0
st.plotly_chart(fig)

st.subheader('Map of NY Hospital Locations')

hospitals_ny_gps = hospitals_ny['location'].str.strip('()').str.split(
    ' ', expand=True).rename(columns={
        0: 'Point',
        1: 'lon',
        2: 'lat'
    })
hospitals_ny_gps['lon'] = hospitals_ny_gps['lon'].str.strip('(')
hospitals_ny_gps = hospitals_ny_gps.dropna()
hospitals_ny_gps['lon'] = pd.to_numeric(hospitals_ny_gps['lon'])
hospitals_ny_gps['lat'] = pd.to_numeric(hospitals_ny_gps['lat'])

st.map(hospitals_ny_gps)

#Timeliness of Care
st.subheader('NY Hospitals - Timelieness of Care')
bar2 = hospitals_ny['timeliness_of_care_national_comparison'].value_counts(
).reset_index()
fig2 = px.bar(bar2, x='index', y='timeliness_of_care_national_comparison')
st.plotly_chart(fig2)

st.markdown(
    'Based on this above bar chart, we can see the majority of hospitals in the NY area fall below the national\
        average as it relates to timeliness of care')

#Drill down into INPATIENT and OUTPATIENT just for NY
st.title('Drill Down into INPATIENT data')
Пример #28
0
    df.set_index("State", inplace=True)
    df["UpdateDateTime"] = pd.to_datetime(df["UpdateDateTime"]).dt.date
    try:
        df.drop(["Unknown"], inplace=True)
    except:
        pass

    if data["State"] != []:
        st.header("State-wise analysis")

        latlongdf = df.reset_index().rename(columns={"Longitude": "lon", "Latitude":"lat"})[['lat', 'lon']]
        latlongdf["lat"] = pd.to_numeric(latlongdf["lat"], errors='coerce')
        latlongdf["lon"] = pd.to_numeric(latlongdf["lon"], errors='coerce')
        
        st.subheader(f"Map of {country}")
        st.map(latlongdf)

        st.subheader(f"Confirmed cases in states of {country}")
        st.write(alt.Chart(df[["Confirmed"]].reset_index()).mark_bar().encode(
            x=alt.X('State', sort=alt.SortField(field="Confirmed", order="descending")),
            y="Confirmed",
            tooltip=["State", "Confirmed"]
        ).properties(width=700, height=500))
        st.subheader(f"Recovered cases in states of {country}")
        st.write(alt.Chart(df[["Recovered"]].reset_index()).mark_bar().encode(
            x=alt.X('State', sort=alt.SortField(field="Recovered", order="descending")),
            y="Recovered",
            tooltip=["State", "Recovered"]
        ).properties(width=700, height=500))
        st.subheader(f"Deaths in states of {country}")
        st.write(alt.Chart(df[["Deaths"]].reset_index()).mark_bar().encode(
Пример #29
0
import numpy as np
import pandas as pd
from PIL import Image

st.title('Streamlit 超入門')

st.write('DataFrame')

df = pd.DataFrame(
    np.random.rand(100,2)/[50,50] + [35.69,139.70],
    columns=['lat','lon']
)
img = Image.open('test.png')
st.image(img,caption='Saotome Ryo',use_column_width=True)

st.map(df)

'''vscode/
st.area_chart(df)
st.line_chart(df)
'''

df = pd.DataFrame({
    '1列目' : [1,2,3,4],
    '2列目' : [10,20,30,40]
})

st.dataframe(df.style.highlight_max(axis=0),width=1000,height=1000)


st.table(df.style.highlight_max(axis=0))
Пример #30
0

def font_size(x):
    st.markdown("""
    <style>
    .big-font {
        font-size:50px !important;
    }
    </style>
    """, unsafe_allow_html=True)

    st.markdown('<p class="big-font">x</p>', unsafe_allow_html=True)


if location == 'Bengaluru':
    st.map(Bengaluru_map)
elif location == 'Chennai':
    st.map(Chennai_map)
elif location == 'Thiruvananthapuram':
    st.map(Thiruvananthapuram_map)
elif location == 'Jaipur':
    st.map(Jaipur_map)
elif location == 'Hyderabad':
    st.map(Hyderabad_map)

st.markdown('AREA CHART')

if location == 'Chennai':
    Chennai_line_chart(model_temp, model_dew, model_hum, model_wind_sp, model_press)
elif location == 'Hyderabad':
    Hyderabad_line_chart(model_temp, model_dew, model_hum, model_wind_sp, model_press)