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
  • 1
    Are you using pandas? Please show some sample data, and what code you've tried so far so that we can help you. Commented Oct 11, 2022 at 13:49

4 Answers 4

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']
Sign up to request clarification or add additional context in comments.

Comments

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

2 Comments

{row[1].zfill(4)} in an fstring is more succinctly written {row[1]:0>4} but perhaps .zfill() is clearer.
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.
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']

Comments

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,

4 Comments

{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.
Apparently you can not: Concatenated_elem = str(Splited[0]) + f'{Splited[1]:04d}' ValueError: Unknown format code 'd' for object of type 'str'
You used 04d, but should have used 0>4
The Concatenated_elem is unnecessarily complicated, the reformatting can be done with a single f-string: f"{Splited[0]}{Splited[1]:0>4}-KG"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.