简体   繁体   English

在Pandas / Python中格式化连接列。

[英]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: 我是Python / Pandas的新手,我正在使用Spyder IDF,通过使用Python 3.6的Anaconda发行版(可能是3.7?)。我通过下面的代码导入一个Excel文件,并想知道如何获得一个看起来很好的输出如下:

VOLTS/PHASE 伏/ PHASE

Currently, the output in Excel is formatted as follows: 目前,Excel中的输出格式如下:

VOLTS.PHASE.0 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?) (另外,我调用的第二列 - PHASE,是一个数字。但是,它将它导出为两位数。 一个常见的例子是它调用1但返回01.这是否与Python假设浮点数有关?我该如何控制?)

I built my code using the following resources: 我使用以下资源构建了我的代码:

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

Combine two columns of text in dataframe in pandas/python 在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()

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? 对于你的第二个问题,你可以运行df [“PHASE”]。dtype并分享该系列的数据类型是什么? If it is a string, then whatever is in excel will be copied exactly. 如果它是一个字符串,那么excel中的任何内容都将被完全复制。 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. 希望有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM