0

Good morning,

I am a new python user and I am trying to replicate the following excel function in python:

=concatenate(left(H2,search(" ",H2,1)-1),if(LEN(right(H2,LEN(H2)-search(" ",H2,1)))=2,"00",if(LEN(right(H2,LEN(H2)-search(" ",H2,1)))=3,"0","")),right(H2,LEN(H2)-search(" ",H2,1)),"-KG")

I am trying to convert Highways into a format my computer program(arcgis) reads, basically turn my csv column format from:

enter image description here

the right column into the left column, so basically keep the two letter in the front (ex. US,FM,SL, CR) adding zeros in front making it a 4 digit highway always and adding "-KG" to the end.

thanks

  • 1
    Are you using pandas? Please show some sample data, and what code you've tried so far so that we can help you. – Chris Oct 11 '22 at 13:49

4 Answers4

1

If using Python lists such as

arr = ['US 90', 'FM 1436', 'SL 305', 'US 277', 'FM 1589', 'SL 480']

do

result = [f'{s}{n:0>4}-KG' for s, n in map(str.split, arr)]

which gives

['US0090-KG', 'FM1436-KG', 'SL0305-KG', 'US0277-KG', 'FM1589-KG', 'SL0480-KG']
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
1

This would look something like:

import csv

with open("yourfile.csv") as fp:
    reader = csv.reader(fp, delimiter=" ")
    output = [[' '.join(row),f'{row[0]}{row[1].zfill(4)}-KG'] for row in reader]

print(output)

[['US 50', 'US0050-KG'], ['CA 987', 'CA0987-KG'], ['IL 4', 'IL0004-KG']]

The zfill() function will left pad a string with the 0 character to make the string the length of the argument (4 in this case)

If you are wanting to write that list of lists back out, check out this answer

JNevill
  • 46,980
  • 4
  • 38
  • 63
  • `{row[1].zfill(4)}` in an fstring is more succinctly written `{row[1]:0>4}` but perhaps `.zfill()` is clearer. – Steven Rumbalski Oct 11 '22 at 14:07
  • 1
    Totally agree. As usual there are a bunch of ways to skin this cat. I already dumped list comprehension in here so tossing in `{row[1]:0>4}` syntax isn't pushing it too far IMO. – JNevill Oct 11 '22 at 14:32
0

This function converts the old highway format into your desired format:

def convert(highway):
    split = highway.split()
    prefix = split[0]
    number = split[1]
    return prefix + (4 - len(number))*"0" + number + "-KG"

If you're working with a pandas dataframe, this converts your whole column:

import pandas as pd

highways = ["US 90", "FM 1436", "SL 305", "US 277", "FM 1689", "SL 480"]

df = pd.DataFrame(highways, columns=["Highways"])
df["Highways"] = df["Highways"].transform(convert, axis=0)

print(df)

Out:

    Highways
0  US0090-KG
1  FM1436-KG
2  SL0305-KG
3  US0277-KG
4  FM1689-KG
5  SL0480-KG

Or if you're using a list:

highways = ["US 90", "FM 1436", "SL 305", "US 277", "FM 1689", "SL 480"]
new_highways = [convert(highway) for highway in highways]
print(new_highways)

Out:

['US0090-KG', 'FM1436-KG', 'SL0305-KG', 'US0277-KG', 'FM1689-KG', 'SL0480-KG']
Timo
  • 357
  • 1
  • 10
0

You can try using the string format instead of zfill: Here's an example it's not for csv but in arcgis I think you wanted to use it in the atributte calculator.

List= ['US 90','FM 1436','SL 305']

for elem in List:
    Splited = str(elem).split(' ')
    Concatenated_elem = str(Splited[0]) + f'{int(Splited[1]):04d}' +'-KG'
    print(Concatenated_elem)

The result in this case is a print:

US0090-KG
FM1436-KG
SL0305-KG

Hope it helps,

SSD93
  • 39
  • 7
  • 1
    `{int(Splited[1]):04d}` can be done without conversion to integer `{Splited[1]:0>4}` where `0` is the pad character, `>` means justify right, and `4` specifies the width. – Steven Rumbalski Oct 11 '22 at 14:21
  • Apparently you can not: `Concatenated_elem = str(Splited[0]) + f'{Splited[1]:04d}'` `ValueError: Unknown format code 'd' for object of type 'str'` – SSD93 Oct 11 '22 at 14:24
  • You used `04d`, but should have used `0>4` – Steven Rumbalski Oct 11 '22 at 14:31
  • 1
    The `Concatenated_elem` is unnecessarily complicated, the reformatting can be done with a single f-string: `f"{Splited[0]}{Splited[1]:0>4}-KG"` – bixb0012 Nov 04 '22 at 14:11