Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting concatenated columns in Pandas/Python.

I am very new to Python/Pandas and am using the Spyder IDF, via the Anaconda distribution with Python 3.6 (maybe 3.7?).I am importing an Excel file via the code below and would like to know how to get an output that looks as follows:

VOLTS/PHASE

Currently, the output in Excel is formatted as follows:

VOLTS.PHASE.0

(Also, the second column I am calling - PHASE, is a single digit. But, it is exporting it as two digits. A common example is that it calls a 1 but returns 01. Does this have something to do with Python assuming floats? How can I control for that?)

I built my code using the following resources:

https://pythonspot.com/en/write-excel-with-pandas/

Combine two columns of text in dataframe in pandas/python

BELOW IS THE CODE I AM USING.

import pandas as pd
from pandas import ExcelWriter
from pandas import ExcelFile


df = pd.read_excel('C:VAV_Schedule1.xlsx', sheetname = 'VAV 1-2')

df["VOLTS/PHASE"] = df["VOLTS"].map(str) + df["PHASE"].map(str)


writer = ExcelWriter('Test2.xlsx')
df.to_excel(writer, 'VAV 1-2', index=True)
writer.save()
like image 977
Mathew Coalson Avatar asked Jan 30 '26 20:01

Mathew Coalson


1 Answers

All you need to do is add + '/' + between the two strings that you are joining.

df["VOLTS/PHASE"] = df["VOLTS"].map(str) + '/' + df["PHASE"].map(str)

For your second question, could you run df["PHASE"].dtype and share what datatype that series is? If it is a string, then whatever is in excel will be copied exactly. One possible solution would be to explicitly convert it to an integer first:

df["VOLTS/PHASE"] = df["VOLTS"].map(str) + '/' + df["PHASE"].astype(int).map(str)

Hope that helps.

like image 191
datanerdjake Avatar answered Feb 01 '26 10:02

datanerdjake



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!