ðŸ’ŧ
Code Snippet
  • Overview
  • General
    • Anaconda
  • GUI
    • PyQT
      • Qt Design
  • Pandas
    • Read Data
    • Replace
  • Articles
    • Python. PyQt
    • Offline Payment Wallet With Django
    • Documentation Encrypt File
    • Play With Pillow
  • Fontend
    • Snippet
    • Hugo
    • JavaScript
      • Form Validation
  • Finance
    • Library
      • yfinance
  • Notebook
    • Untitled
    • Snippet
  • Python
    • Download file
    • Date and Time
    • Snippet
    • Compile .exe
    • Overview
    • Google
      • Samples for Google Workspace
      • Drive
      • GoogleSheet
    • Virtual environment
    • Database
      • Pickle()
    • Datatypes
      • Excel
      • Dictionary
        • xmltodict()
    • File Handling
      • shutil()
      • Get the File Name
      • Get the Full Path
      • Check the File Size
      • Get File Creation Date
      • Find All File
        • Untitled
    • Dictionary
      • Convert Two Lists
  • Data Science
    • HTTP requests
  • Google Workspace
    • Overview
    • Apps Script
      • āđŒNote
      • Overview
      • Snippet
        • HTML Service
        • Fetch API
      • Quickstart
      • Google Sheets
        • Overview
          • Snippet
        • Fundamentals
          • Macros & Custom Functions
          • Spreadsheets, Sheets, and Ranges
          • Working with Data
          • Data Formatting
          • Chart and Present Data
        • Built-in Google Services
        • Fetch and format API data
        • Connected Sheets
  • Git
  • Mini Lab
    • Line
    • Python
  • Function
    • Python
      • Date&Time
  • Database
    • SQLite
      • Example
Powered by GitBook
On this page
  • Clipboard
  • āļāļģāļŦāļ™āļ”āļŠāļ·āđˆāļ­ Column āđ€āļ­āļ‡
  • SQL
  • Text
  • Read text from URL

Was this helpful?

  1. Pandas

Read Data

Clipboard

df = pd.read_clipboard()

āļāļģāļŦāļ™āļ”āļŠāļ·āđˆāļ­ Column āđ€āļ­āļ‡

n = ['No', 'County', 'Currency', 'Currency Code', 'Export', 'Import']
df = pd.read_clipboard(header=None,names=n)

SQL

import sqlite3
import random
import pandas as pd
import matplotlib.pyplot as plt


def create_table(db):
    try:
        with sqlite3.connect(db) as con:
            sql_cmd = '''
             DROP TABLE IF EXISTS person;
             CREATE TABLE person(
                 obs INTEGER PRIMARY KEY AUTOINCREMENT,
                 gender TEXT,
                 weight REAL,
                 height REAL);
             '''
            con.executescript(sql_cmd)
    except Exception as e:
        print('Error -> {}'.format(e))


def create_data(db, rows=10):
    data = [(
        random.choice('MF'),
        random.normalvariate(57, 4.5),
        random.normalvariate(160, 6),
    ) for _ in range(rows)]
    print(data)
    try:
        with sqlite3.connect(db) as con:
            sql_cmd = 'INSERT INTO person(gender, weight, height) VALUES (?, ?, ?);'
            con.executemany(sql_cmd, data)
    except Exception as e:
        print('Error -> {}'.format(e))


def pd_read_sql(db):
    with sqlite3.connect(db) as con:
        sql_cmd = '''
          SELECT obs, gender, weight, height 
            FROM person 
            ORDER BY height'''
        df = pd.read_sql(sql_cmd,
                         con, index_col='obs')
    print(df)
    df['bmi'] = df.weight / (df.height / 100) ** 2
    # df['height'].plot.hist(alpha=.7)
    # df.plot.bar(x=df.index, y='weight')
    df.plot.scatter(x='weight', y='height')
    print(f'mean(bmi) = {df.bmi.mean():.2f}')  # f-string in Python 3.6 (php: variable substitution, c#: string interpolation
    plt.show()


if __name__ == '__main__':
    db = 'sample.sqlite'
    create_table(db)
    create_data(db, 100)
    pd_read_sql(db)

Text

Read text from URL

import urllib.request


# https://dl.dropboxusercontent.com/u/23148470/planet.txt

def read_from_url(link):
    with urllib.request.urlopen(link) as f:
        s = f.read()
    # print(s)
    # print(type(s))
    # s1 = s.decode("utf8")
    # print(type(s1))
    # print(s1)
    return s.decode("utf8")


def read_from_url2(link):
    with urllib.request.urlopen(link) as f:
        for line in f:
            # print("- {}".format(line))
            print("- {}".format(line.decode("utf8")), end="")
            # print(s)
            # print(type(s))
            # s1 = s.decode("utf8")
            # print(type(s1))
            # print(s1)


t = read_from_url("https://dl.dropboxusercontent.com/u/23148470/planet.txt")
print("t = ", t)
lines = t.splitlines()
print("lines = ", lines)
# read_from_url2("https://dl.dropboxusercontent.com/u/23148470/planet.txt")
PreviousPandasNextReplace

Last updated 3 years ago

Was this helpful?