Connecting data in python to spreadsheets - python

I have a dictionary in Python 2.7.9. I want to present the data in my dictionary in a spreadsheet. How can I accomplish this? Note, the dictionary has over 15 different items inside.
Dictionary:
{'Leda Doggslife': '$13.99', 'Carson Busses': '$29.95', 'Derri Anne Connecticut': '$19.25', 'Bobbi Soks': '$5.68', 'Ben D. Rules': '$7.50', 'Patty Cakes': '$15.26', 'Ira Pent': '$16.27', 'Moe Tell': '$10.09', 'Ido Hoe': '$14.47', 'Ave Sectomy': '$50.85', 'Phil Meup': '$15.98', 'Al Fresco': '$8.49', 'Moe Dess': '$19.25', 'Sheila Takya': '$15.00', 'Earl E. Byrd': '$8.37', 'Rose Tattoo': '$114.07', 'Gary Shattire': '$14.26', 'Len Lease': '$11.11', 'Howie Kisses': '$15.86', 'Dan Druff': '$31.57'}

Are you trying to write your dictionary in a Excel Spreadsheet?
In this case, you could use win32com library:
import win32com.client
xlApp = win32com.client.DispatchEx('Excel.Application')
xlApp.Visible = 0
xlBook = xlApp.Workbooks.Open(my_filename)
sht = xlBook.Worksheets(my_sheet)
row = 1
for element in dict.keys():
sht.Cells(row, 1).Value = element
sht.Cells(row, 2).Value = dict[element]
row += 1
xlBook.Save()
xlBook.Close()
Note that this code will work just if the workbook already exists.
Otherwise:
import win32com.client
xlApp = win32com.client.DispatchEx('Excel.Application')
xlApp.Visible = 0
xlBook = xlApp.Workbooks.Add()
sht = xlBook.Worksheets(my_sheet)
row = 1
for element in dict.keys():
sht.Cells(row, 1).Value = element
sht.Cells(row, 2).Value = dict[element]
row += 1
xlBook.SaveAs(mw_filename)
xlBook.Close()
I hope it will be the right answer to your question.

Related

Python openpyxl add a new column

I have an .xlsx file like this:
item price
foo 5$
poo 3$
woo 7$
moo 2$
I want to use the openpyxl to open the file and add a new column to it like this:
item price owner
foo 5$ Jim owns foo
poo 3$ Jack owns poo
woo 7$ John owns woo
moo 2$ Jay owns moo
Anyone can help me with how to do it?
My code:
file_location = 'excel_name.xlsx'
df = pd.read_excel(file_errors_location, engine='openpyxl')
for item in df['item']:
df['sub'].append(f'bla bla owms {item}')
df.to_excel('excel_me.xlsx', engine='openpyxl')
You don't need pandas for something this simple.
So working with 'item' column as column 'A'
import openpyxl as op
wb = op.load_workbook(r'foo.xlsx')
ws = wb["Sheet1"]
owner_list = ['owner', 'Jim', 'Jack', 'John', 'Jay']
for enum, cell in enumerate(ws['A']):
row = enum+1
if enum == 0:
ws.cell(row=row, column=3).value = owner_list[enum]
else:
ws.cell(row=row, column=3).value = owner_list[enum] + " owns " + cell.value
wb.save('foo.xlsx')

nested drop downs with xlwings

I'm trying to generate nested drop downs with xlwings, a python module enabling linking python scripts to VBA functions. I was able to do this using the xslxwriter module using excel's =indirect(cell) formula but I can't seem to find any equivalent in xlwings.
Well trying to refine my question I found the answer.
Here is how to do nested drop downs with xlsxwriter.
import xlsxwriter
# open workbook
workbook = xlsxwriter.Workbook('nested_drop_downs_with_xlsxwriter.xlsx')
# data
countries = ['Mexico', 'USA', 'Canada']
mexican_cities = ['Morelia', 'Cancun', 'Puebla']
usa_cities = ['Chicago', 'Florida', 'Boston']
canada_cities = ['Montreal', 'Toronto', 'Vancouver']
# add data to workbook
worksheet = workbook.add_worksheet("sheet1")
worksheet.write_column(0, 0, countries)
worksheet.write(0, 1, countries[0])
worksheet.write_column(1, 1, mexican_cities)
worksheet.write(0, 2, countries[1])
worksheet.write_column(1, 2, usa_cities)
worksheet.write(0, 3, countries[2])
worksheet.write_column(1, 3, canada_cities)
# name regions
workbook.define_name('Mexico', '=sheet1!$B2:$B4')
workbook.define_name('USA', '=sheet1!$C2:$C4')
workbook.define_name('Canada', '=sheet1!$D2:$D4')
#
worksheet.data_validation('A10', {'validate': 'list', 'source': '=sheet1!$A$1:$A$3'})
worksheet.data_validation('B10', {'validate': 'list', 'source': '=INDIRECT($A$10)'})
workbook.close()
And here is how to do nested drop downs with xlwings:
def main():
wb = xw.Book.caller()
sheet = wb.sheets('Sheet1')
# data
countries = ['Mexico', 'USA', 'Canada']
mexican_cities = ['Morelia', 'Cancun', 'Puebla']
usa_cities = ['Chicago', 'Florida', 'Boston']
canada_cities = ['Montreal', 'Toronto', 'Vancouver']
# add data to workbook
sheet.range('A1:A3').options(transpose=True).value = countries
sheet.range('B1').value = countries[0]
sheet.range('B2').options(transpose=True).value= mexican_cities
sheet.range('C1').value = countries[1]
sheet.range('C2').options(transpose=True).value = usa_cities
sheet.range('D1').value = countries[2]
sheet.range('D2').options(transpose=True).value = canada_cities
# name regions <-------- naming regions with a dollar sign was the fix!
sheet.range('$B$2:$B$4').api.name.set('Mexico')
sheet.range('$C$2:$C$4').api.name.set('USA')
sheet.range('$D$2:$D$4').api.name.set('Canada')
sheet.range('A10').api.validation.delete()
sheet.range('A10').api.validation.add_data_validation(type=3, formula1='=Sheet1!$A$1:$A$3')
sheet.range('B10').api.validation.delete()
sheet.range('B10').api.validation.add_data_validation(type=3, formula1='=INDIRECT($A$10)')
if __name__ == "__main__":
xw.Book("demo1.xlsm").set_mock_caller()
main()

How to extract text and save as excel file using python or JavaScript

How do I extract text from this PDF files where some data is in the form of table while some are key value based data
eg:
https://drive.internxt.com/s/file/78f2d73478b832b2ab55/3edb275967deeca6ad33e7d53f2337c50d5dfb50e0aa525bb7f10d49dff1e2b4
This is what I have tried :
import PyPDF2
import openpyxl
from openpyxl import Workbook
pdfFileObj = open('sample.pdf', 'rb')
pdfReader = PyPDF2.PdfFileReader(pdfFileObj)
pdfReader.numPages
pageObj = pdfReader.getPage(0)
mytext = pageObj.extractText()
wb = Workbook()
sheet = wb.active
sheet.title = 'MyPDF'
sheet['A1'] = mytext
wb.save('sample.xlsx')
print('Save')
However I'd like the data to be stored in the following format.
This pdf does not have well defined tables, hence cannot use any tool to extract the entire data in one table format. What we can do is read the entire pdf as text. And process each data fields line by line by using regex to extract the data.
Before you move ahead, please install the pdfplumber package for python
pip install pdfplumber
Assumptions
Here are some assumptions that I made for your pdf and accordingly I have written the code.
First line will always contain the title Account History Report.
Second line will contain the names IMAGE All Notes
Third line will contain only the data Date Created in the form of key:value.
Fourth line will contain only the data Number of Pages in the form of key:value.
Fifth line will only contain the data Client Code, Client Name
Starting line 6, a pdf can have multiple data entity, these data entity for eg in this pdf is 2 but can be any number of entity.
Each data entity will contain the following fields:
First line in data entity will contain only the data Our Ref, Name, Ref 1, Ref 2
Second line line will only contain data in the form as present in pdf Amount, Total Paid, Balance, Date of A/C, Date Received
Third line in data entity will contain the data Last Paid, Amt Last Paid, Status, Collector.
Fourth line will contain the column name Date Notes
The subsequent lines will contain data in the form of table until the next data entity is started.
I also assume that each data entity will contain the first data with key Our Ref :.
I assume that the data entity will be separated on the first line of each entity in the pattern of key values as Our Ref :Value Name: Value Ref 1 :Value Ref 2:value
pattern = r'Our Ref.*?Name.*?Ref 1.*?Ref 2.*?'
Please note that the rectangle that I have created(thick black) in above image, I am calling those as data entity.
The final data will be stored in a dictionary(json) where the data entity will have key as dataentity1, dataentity2, dataentity3 based on the number of entities you have in your pdf.
The header details are stored in the json as key:value and I assume that each key will be present in header only once.
CODE
Here is the simple elegant code, that gives you information from the pdf in the form of json. In the output the first few field contains information from the header part, subsequent data entities can be found as data_entity 1 and 2.
In the below code all you need to change is pdf_path.
import pdfplumber
import re
# regex pattern for keys in line1 of data entity
my_regex_dict_line1 = {
'Our Ref' : r'Our Ref :(.*?)Name',
'Name' : r'Name:(.*?)Ref 1',
'Ref 1' : r'Ref 1 :(.*?)Ref 2',
'Ref 2' : r'Ref 2:(.*?)$'
}
# regex pattern for keys in line2 of data entity
my_regex_dict_line2 = {
'Amount' : r'Amount:(.*?)Total Paid',
'Total Paid' : r'Total Paid:(.*?)Balance',
'Balance' : r'Balance:(.*?)Date of A/C',
'Date of A/C' : r'Date of A/C:(.*?)Date Received',
'Date Received' : r'Date Received:(.*?)$'
}
# regex pattern for keys in line3 of data entity
my_regex_dict_line3 ={
'Last Paid' : r'Last Paid:(.*?)Amt Last Paid',
'Amt Last Paid' : r'Amt Last Paid:(.*?)A/C\s+Status',
'A/C Status': r'A/C\s+Status:(.*?)Collector',
'Collector' : r'Collector :(.*?)$'
}
def preprocess_data(data):
return [el.strip() for el in data.splitlines() if el.strip()]
def get_header_data(text, json_data = {}):
header_data_list = preprocess_data(text)
# third line in text of header contains Date Created field
json_data['Date Created'] = re.search(r'Date Created:(.*?)$', header_data_list[2]).group(1).strip()
# fourth line in text contains Number of Pages, Client Code, Client Name
json_data['Number of Pages'] = re.search(r'Number of Pages:(.*?)$', header_data_list[3]).group(1).strip()
# fifth line in text contains Client Code and ClientName
json_data['Client Code'] = re.search(r'Client Code - (.*?)Client Name', header_data_list[4]).group(1).strip()
json_data['ClientName'] = re.search(r'Client Name - (.*?)$', header_data_list[4]).group(1).strip()
def iterate_through_regex_and_populate_dictionaries(data_dict, regex_dict, text):
''' For the given pattern of regex_dict, this function iterates through each regex pattern and adds the key value to regex_dict dictionary '''
for key, regex in regex_dict.items():
matched_value = re.search(regex, text)
if matched_value is not None:
data_dict[key] = matched_value.group(1).strip()
def populate_date_notes(data_dict, text):
''' This function populates date and Notes in the data chunk in the form of list to data_dict dictionary '''
data_dict['Date'] = []
data_dict['Notes'] = []
iter = 4
while(iter < len(text)):
date_match = re.search(r'(\d{2}/\d{2}/\d{4})',text[iter])
data_dict['Date'].append(date_match.group(1).strip())
notes_match = re.search(r'\d{2}/\d{2}/\d{4}\s*(.*?)$',text[iter])
data_dict['Notes'].append(notes_match.group(1).strip())
iter += 1
data_index = 1
json_data = {}
pdf_path = r'C:\Users\hpoddar\Desktop\Temp\sample3.pdf' # ENTER YOUR PDF PATH HERE
pdf_text = ''
data_entity_sep_pattern = r'(?=Our Ref.*?Name.*?Ref 1.*?Ref 2)'
if(__name__ == '__main__'):
with pdfplumber.open(pdf_path) as pdf:
index = 0
while(index < len(pdf.pages)):
page = pdf.pages[index]
pdf_text += '\n' + page.extract_text()
index += 1
split_on_data_entity = re.split(data_entity_sep_pattern, pdf_text.strip())
# first data in the split_on_data_entity list will contain the header information
get_header_data(split_on_data_entity[0], json_data)
while(data_index < len(split_on_data_entity)):
data_entity = {}
data_processed = preprocess_data(split_on_data_entity[data_index])
iterate_through_regex_and_populate_dictionaries(data_entity, my_regex_dict_line1, data_processed[0])
iterate_through_regex_and_populate_dictionaries(data_entity, my_regex_dict_line2, data_processed[1])
iterate_through_regex_and_populate_dictionaries(data_entity, my_regex_dict_line3, data_processed[2])
if(len(data_processed) > 3 and data_processed[3] != None and 'Date' in data_processed[3] and 'Notes' in data_processed[3]):
populate_date_notes(data_entity, data_processed)
json_data['data_entity' + str(data_index)] = data_entity
data_index += 1
print(json_data)
Output :
Result string :
{'Date Created': '18/04/2022', 'Number of Pages': '4', 'Client Code': '110203', 'ClientName': 'AWS PTE. LTD.', 'data_entity1': {'Our Ref': '2118881115', 'Name': 'Sky Blue', 'Ref 1': '12-34-56789-2021/2', 'Ref 2': 'F2021004444', 'Amount': '$100.11', 'Total Paid': '$0.00', 'Balance': '$100.11', 'Date of A/C': '01/08/2021', 'Date Received': '10/12/2021', 'Last Paid': '', 'Amt Last Paid': '', 'A/C Status': 'CLOSED', 'Collector': 'Sunny Jane', 'Date': ['04/03/2022'], 'Notes': ['Letter Dated 04 Mar 2022.']}, 'data_entity2': {'Our Ref': '2112221119', 'Name': 'Green Field', 'Ref 1': '98-76-54321-2021/1', 'Ref 2': 'F2021001111', 'Amount': '$233.88', 'Total Paid': '$0.00', 'Balance': '$233.88', 'Date of A/C': '01/08/2021', 'Date Received': '10/12/2021', 'Last Paid': '', 'Amt Last Paid': '', 'A/C Status': 'CURRENT', 'Collector': 'Sam Jason', 'Date': ['11/03/2022', '11/03/2022', '08/03/2022', '08/03/2022', '21/02/2022', '18/02/2022', '18/02/2022'], 'Notes': ['Email for payment', 'Case Status', 'to send a Letter', '845***Ringing, No reply', 'Letter printed - LET: LETTER 2', 'Letter sent - LET: LETTER 2', '845***Line busy']}}
Now once you got the data in the json format, you can load it in a csv file, as a data frame or whatever format you need the data to be in.
Save as xlsx
To save the same in a xlsx file in the format as shown in the image in the question above. We can use xlsx writer to do the same.
Please install the package using pip
pip install xlsxwriter
From the previous code, we have our entire data in the variable json_data, we will be iterating through all the data entities and write the data to appropriate cell specified by row, col in the code.
import xlsxwriter
workbook = xlsxwriter.Workbook('Sample.xlsx')
worksheet = workbook.add_worksheet("Sheet 1")
row = 0
col = 0
# write columns
columns = ['Account History Report', 'All Notes'] + [ key for key in json_data.keys() if 'data_entity' not in key ] + list(json_data['data_entity1'].keys())
worksheet.write_row(row, col, tuple(columns))
row += 1
column_index_map = {}
for index, col in enumerate(columns):
column_index_map[col] = index
# write the header
worksheet.write(row, column_index_map['Date Created'], json_data['Date Created'])
worksheet.write(row, column_index_map['Number of Pages'], json_data['Number of Pages'])
worksheet.write(row, column_index_map['Client Code'], json_data['Client Code'])
worksheet.write(row, column_index_map['ClientName'], json_data['ClientName'])
data_entity_index = 1
#iterate through each data entity and for each key insert the values in the sheet
while True:
data_entity_key = 'data_entity' + str(data_entity_index)
row_size = 1
if(json_data.get(data_entity_key) != None):
for key, value in json_data.get(data_entity_key).items():
if(type(value) == list):
worksheet.write_column(row, column_index_map[key], tuple(value))
row_size = len(value)
else:
worksheet.write(row, column_index_map[key], value)
else:
break
data_entity_index += 1
row += row_size
workbook.close()
Result :
The above code creates a file sample.xlsx in the working directory.

Looking over a csv file for various conditions

00,0,6098
00,1,6098
00,2,6098
00,3,6098
00,4,6094
00,5,6094
01,0,8749
01,1,8749
01,2,8749
01,3,88609
01,4,88609
01,5,88609
01,6,88611
01,7,88611
01,8,88611
02,0,9006
02,1,9006
02,2,4355
02,3,9013
02,4,9013
02,5,9013
02,6,4341
02,7,4341
02,8,4341
02,9,4341
03,0,6285
03,1,6285
03,2,6285
03,3,6285
03,4,6278
03,5,6278
03,6,6278
03,7,6278
03,8,8960
I have a csv file and a bit of it is shown above.
What I want to do is if the column 0 has the same value, it makes a an array of column 2, prints the array. ie- for 00, it makes an array-
a = [6098,6098,6098,6098,6094,6094]
for 01, it makes an array-
a = [8749,8749,88609,88609,88609,88611,88611,88611]
I don't know how to loop over this file.
This solution assumes that the first column will appear in sorted order in the file.
def main():
import csv
from itertools import groupby
with open("csv.csv") as file:
reader = csv.reader(file)
rows = [[row[0]] + [int(item) for item in row[1:]] for row in reader]
groups = {}
for key, group in groupby(rows, lambda row: row[0]):
groups[key] = [row[2] for row in group]
print(groups["00"])
print(groups["01"])
print(groups["02"])
print(groups["03"])
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Output:
[6098, 6098, 6098, 6098, 6094, 6094]
[8749, 8749, 8749, 88609, 88609, 88609, 88611, 88611, 88611]
[9006, 9006, 4355, 9013, 9013, 9013, 4341, 4341, 4341, 4341]
[6285, 6285, 6285, 6285, 6278, 6278, 6278, 6278, 8960]
The idea is to use a dictionary in which 00, 01 etc will be the keys and value will be a list. So you need to iterate through the csv data and push these data to corresponding keys.
import csv
result = {}
with open("you csv file", "r") as csvfile:
data = csv.reader(csvfile)
for row in data:
if result.has_key(row[0]):
result[row[0]].append(row[2])
else:
result[row[0]] = [row[2]]
print (result)
Here
from collections import defaultdict
txt = '''00,0,6098
00,1,6098
00,2,6098
00,3,6098
00,4,6094
00,5,6094
01,0,8749
01,1,8749
01,2,8749
01,3,88609
01,4,88609
01,5,88609
01,6,88611
01,7,88611
01,8,88611
02,0,9006
02,1,9006
02,2,4355
02,3,9013
02,4,9013
02,5,9013
02,6,4341
02,7,4341
02,8,4341
02,9,4341
03,0,6285
03,1,6285
03,2,6285
03,3,6285
03,4,6278
03,5,6278
03,6,6278
03,7,6278
03,8,8960'''
data_holder = defaultdict(list)
lines = txt.split('\n')
for line in lines:
fields = line.split(',')
data_holder[fields[0]].append(fields[2])
for k,v in data_holder.items():
print('{} -> {}'.format(k,v))
output
02 -> ['9006', '9006', '4355', '9013', '9013', '9013', '4341', '4341', '4341', '4341']
03 -> ['6285', '6285', '6285', '6285', '6278', '6278', '6278', '6278', '8960']
00 -> ['6098', '6098', '6098', '6098', '6094', '6094']
01 -> ['8749', '8749', '8749', '88609', '88609', '88609', '88611', '88611', '88611']

How to convert Pandas object and not the entire dataframe to string?

While reading the csv file, I am iterating over it using itertuples:
df = pd.read_csv("/home/aviral/dev/misc/EKYducHrK93oSKCt7nY0ZYne.csv", encoding='utf-8')
count = 0
for row in df.itertuples():
print (row)
if count == 0:
sys.exit()
count += 1
The value of row is:
Pandas(Index=0, _1='07755aa8-3a15-42ca-8757-58da8a9a298f', _2=nan,
_3='07755aa8-3a15-42ca-8757-58da8a9a298f', _4='2018-03-14T04:43:21.309Z', _5='2018-03-14T04:43:30.679Z', _6='2018-03-14T04:43:30.679Z', User='Vaibhav Inzalkar', Username=919766148649, _9=24, _10=24, _11='Android',
_12='6E6498d700e51ebf', _13='2.3.0', _14='2.3.0', _15=nan, Tags=nan, vill_name='911B675b-B422-41E9-A2ae-6Ccb1e9de2e4', vill_name_parent_response_id='02d93f9d-80df-4e12-8c6b-4c7859a50862', vill_name_taluka_code=4082, census_district_2011='Yavatmal', vill_name_gp_code=194782, vill_name_village_code=542432.0, subdistrict_code=4082, vill_name_anganwadi_code=27510160609.0, census_village_sd_2011='Dhamani', district_code=510, vill_name_taluka_name='Yavatmal', vill_name_gp_name='Dhamni', vill_name_staffname='Anjali Rajendra Pachkawade', vill_name_gram_panchayat_survey_phase='Phase_3', census_subdistrict_2011='Yavatmal', vill_name_auditor_mobile_number=919766148649, vill_name_auditor_name='Vaibhav Inzalkar', vill_name_dist_sd_vill_comb_code=5104082194782542848, vill_name_anganwadi_worker_mobile_number=9404825268.0, _36=nan, buildtype='Pucca House', buildown='Temporary Arrangement', _39=1,
_40=1, staffname='Anjali Rajendra Pachakawde', anganwadi_sevika_own_mobile_yn=nan, anganwadi_worker_mobile_number=nan, wrkrvillyn='Yes', sahayakname='Pandharnishe Madam', helpervillyn='Yes', pregno=6, mothlactano=6, _49=1, imr_child_birth=3, imr_child_deaths=1, child0to6no=43, _53=1.0, angawadi_children_not_suffering_from_sam_age_zero_six=42.0, _55=0.0, adolegirlno=0, _57=nan, _58=1, _59=1, _60=1, _61=0, _62=1, _63=0,
_64=1, _65=1, _66=0, _67=0, _68=0, _69=0, _70=0, _71=0, _72=0, _73=0, _74=0, _75=0, _76=1, _77=0, _78=0, drugs_nothing=0, drugs_nothing_646PdPW9FewY3edC2LeG=0, _81=0, _82=0, _83=0, _84=0,
_85=0, _86=1, _87=1, _88=0, _89=0, _90=0, _91=0, _92=0, _93=0, _94=0, _95=0, _96=0, infraphy_nota=0, basic_util_awc_Register=0, _99=1, _100=1, _101=0, _102=0, _103=0, basic_util_awc_Ventilation=0, _105=0, _106=1, _107=1, _108=1, _109=1, basic_util_awc_Phenyl=1, basic_util_awc_Register_2DN84oFiz565JzqFegx7=0, _112=0, _113=0,
_114=0, _115=0, _116=0, basic_util_awc_Ventilation_2DN84oFiz565JzqFegx7=0, _118=0, _119=0,
_120=0, _121=0, _122=0, basic_util_awc_Phenyl_2DN84oFiz565JzqFegx7=0, basic_util_awc_nota=0, solar_unit=nan, elec_bill_paid=nan, _127=nan,
_128=nan, _129=nan, _130=nan, _131=nan, _132=nan, _133=nan, _134=nan, _135=nan, _136=nan, other=nan, _138=1, _139=1, _140=1, _141=1, _142=1, _143=1, _144=1, _145=0, _146=0, _147=0, _148=0, _149=0, _150=0, _151=0, servpregbaby03_nota=0, anganwadi_children_vaccination_BCG=1.0, anganwadi_children_vaccination_DPT=1.0, anganwadi_children_vaccination_OPV=1.0, _156=0.0, anganwadi_children_vaccination_Measles=1.0, _158=1.0, _159=1.0,
_160=0.0, _161=0.0, _162=0.0, anganwadi_children_vaccination_nota=0.0, _164=1, _165=1, _166=1, _167=1, _168=0, _169=0, _170=0, _171=0, servchild3to6_nota=0, servadolgirl_registration=0, _174=0, _175=0,
_176=0, _177=0, servadolgirl_registration_KoXmKreRO4DAxGuLelRP=0, _179=0, _180=0, _181=0, _182=0, servadolgirl_nothing=0, servadolgirl_nothing_KoXmKreRO4DAxGuLelRP=1, anganwadi_photo='Https://Collect-V2-Production.s3.Ap-South-1.Amazonaws.com/Omurh3lmkcmftts4muxn%2Fwmse68bvz5zwmzcfj9tx%2Fcpo0bvh0kuday74e9cqw%2F94c13850-6008-4087-B742-7B31ad2e4d02.Jpeg', anganwadi_map_latitude=20.338352399999998, anganwadi_map_longitude=78.1930695, anganwadi_map_accuracy=10.0,
_189=nan, problem_1='1)Pakki Building', problem_2='1) Toilet', problem_3='Kichan', problem_4='Elictric Line', problem_5='Water Connection', popserv=55, census_country='India', state_name='Maharashtra', state_code=27, sc_ang_id=1, village_code_census2011_raw=542432.0, phase='Phase 3')
How can I get just the columns and the values?
Something just like this:
_1='07755aa8-3a15-42ca-8757-58da8a9a298f', _2=nan, _3='07755aa8-3a15-42ca-8757-58da8a9a298f', _4='2018-03-14T04:43:21.309Z', _5='2018-03-14T04:43:30.679Z', _6='2018-03-14T04:43:30.679Z', User='Vaibhav Inzalkar', Username=919766148649, _9=24, _10=24, _11='Android',
_12='6E6498d700e51ebf', _13='2.3.0', _14='2.3.0'
Something like this?
Sample dataframe
name city cell
0 A X 124
1 ABC Y 345
2 BAD Z 76
Code:
for i in df.itertuples():
# Python 3.6
print(','.join(f' {j}="{getattr(i,j)}"' for j in df.columns))
# Python 3.5
print(','.join(' {0}="{1}"'.format(j, getattr(i,j)) for j in df.columns))
Output:
name="A", city="X", cell="124"
name="ABC", city="Y", cell="345"
name="BAD", city="Z", cell="76"
Writing to file:
with open("dummy.json", "a+") as f:
for i in df.itertuples():
x = dict(i._asdict())
json.dump(x, f)
f.write("\n")

Categories