Forgot Password,

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

You must login to ask a question.

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

databaseanswers.net Latest Questions

  • 1
Clara
Beginner

How to load information in two columns?

Question 1: The file phone.txt stores the lines in the format code:number

enter image description here

import pandas as pd
import sqlite3

con = sqlite3.connect('database.db')
data = pd.read_csv('phone.txt', sep='\t', header=None)
data.to_sql('post_table', con, if_exists='replace', index=False)

I want to load all the data from the phone.txt file into the database.db database. But I have everything loaded in one column. And I need to load in two columns:

  1. code
  2. number

How to do it?

Question 2: after downloading the information to the database, how can I find the number by code? For example, if I want to find out what number code = 7 (answer: 9062621390).

Related Questions

Leave an answer

You must login to add an answer.

1 Answer

  1. Question 1

    In your example pandas is not able to distinguish between the code and the number since your file is :-separated. When reading your file you need to change the separator to : and also specify columns since your csv doesn’t seem to have a header like so

    data = pd.read_csv('phone.txt',
                       sep=':',
                       names=['code', 'number'])
    

    Question 2

    After putting your data to the database you can query it as follows

    number = pd.read_sql_query('SELECT number FROM post_table WHERE code = (?)',
                               con,
                               params=(code,))
    

    where con is your sqlite connection.