Skip to content Skip to sidebar Skip to footer

Change Numerical Data To Text In Csv File

The below query is grabbing data and creating a CSV file, the issue that I am having is that the source called ‘SPLE’ stores data in the database with numbers of 0, 1, 50. Howe

Solution 1:

You can change the value before you write it to the csv:

mapping = {0:  "True",
           1:  "False",
           50: "Pending"}
# Map `SPLE`
sple = my_dict['SPLE']
my_dict['SPLE'] = mapping.get(int(sple), sple)

# Map `NME`
nme = my_dict['NME']
my_dict['NME'] = mapping.get(int(nme), nme)


w.writerow(my_dict)

Solution 2:

Without seeing the contents of my_dict, this is just a best guess but I'll try and assist stating my assumptions.

For a my_dict that is like the following:

my_dict = {"DATE": ..., "SPLE": ..., ...}

Before w.writerow(my_dict) you could parse the SPLE entry into what you want with:

my_dict["SPLE"] = str(bool(int(my_dict["SPLE"]))) ifint(my_dict["SPLE"]) in [0,1] else"Pending"

The is a compact form of:

# Check to see if current "SPLE" value can be described 
# asTrue (1) orFalse (0)
if int(my_dict["SPLE"]) in [0,1]:
    # Yes it can, so change it toTrueorFalsestringby type conversion
    my_dict["SPLE"] = str(bool(int(my_dict["SPLE"])))
else:
    # Entry isnot a 0or1 so not described bytrueorfalse
    # assign to"Pending"
    my_dict["SPLE"] = "Pending"

Post a Comment for "Change Numerical Data To Text In Csv File"