Conversion Text to Number in Python

Conversion text to number in python

You can use the strings_to_numbers XlsxWriter constructor option. From the docs:

strings_to_numbers: Enable the worksheet.write() method to convert strings to numbers, where possible, using float() in order to avoid an Excel warning about “Numbers Stored as Text”. The default is False. To enable this option use:

workbook = xlsxwriter.Workbook(filename, {'strings_to_numbers': True})

Example:

import xlsxwriter

workbook = xlsxwriter.Workbook('test.xlsx', {'strings_to_numbers': True})
worksheet = workbook.add_worksheet()

worksheet.write(0, 0, 'Hello')
worksheet.write(1, 0, '123') # Write this string as a number.

workbook.close()

Output:

Sample Image

How do I parse a string to a float or int?

>>> a = "545.2222"
>>> float(a)
545.22220000000004
>>> int(float(a))
545

Convert text number composed of 2 different numbers to digits

Seems like its submodule alpha2digit does support it, you just need to further split and join the result to get the expected output:

from text_to_num import alpha2digit

''.join(alpha2digit("thirty six seventy two", lang='en').split())
# '3672'

''.join(alpha2digit("eighty two fifty", lang='en').split())
# '8250'

convert text/string to number/int for python dataframe

import pandas as pd 

fruitList={'name':[ "Apple","Orange","Apple","Banana","Blackberries","Avocado","Grapes","Orange","Apple","Mango"] }
df = pd.DataFrame(fruitList)

# get distinct fruit names
unique=df.name.unique()
# generating a dictionary based on Id of unique fruit names using list comprehension
dict={ x:index+1 for index, x in enumerate(unique) }
# assigning new column 'Id' values from the dictionary using the map function
df['Id'] = df["name"].map(dict)
print(df)

The Output is :

        name      Id
0 Apple 1
1 Orange 2
2 Apple 1
3 Banana 3
4 Blackberries 4
5 Avocado 5
6 Grapes 6
7 Orange 2
8 Apple 1
9 Mango 7

How can I convert Cell of Openpyxl from Text to Number format?

the read data from txt file will be in string. So, as suggested by jezza, you need to convert list to float. You don't need the 'number_format` lines you have. Updated code is here. Note that the conversion map assumes all data can be converted to float (no text). The try/catch will basically skip the row if there is text on any row

import csv
#import openpyxl
import openpyxl as oxl

input_file = r'C:\Python\Test.txt'
output_file = r'C:\Python\Test.xlsx'

wb = oxl.Workbook()
ws = wb.active
#ws.number_format = 'General'
ws.title = "Waveform"
#ws = wb.create_sheet(title='Waveform')

with open(input_file, 'r') as data:
reader = csv.reader(data, delimiter='\t')
for row in reader:
try:
row = list(map(float, row))
ws.append(row)
except:
print("Skipping row ", row)
pass

#for row in range(2, ws.max_row+1):
# ws["{}{}".format("A", row)].number_format = 'General'
# ws["{}{}".format("B", row)].number_format = 'General'

wb.save(output_file)

Output

Sample Image



Related Topics



Leave a reply



Submit