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

时间:2017-10-04 15:27:32

标签: python excel pandas

我是Python / Pandas的新手,我正在使用Spyder IDF,通过使用Python 3.6的Anaconda发行版(可能是3.7?)。我通过下面的代码导入Excel文件,并想知道如何获得输出看起来如下:

伏/ PHASE

目前,Excel中的输出格式如下:

VOLTS.PHASE.0

(另外,我调用的第二列 - PHASE,是一个数字。但是,它将它输出为两位数。一个常见的例子是它调用1但返回01。这是否与Python假设浮动有关?我如何控制它?)

我使用以下资源构建了我的代码:

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

Combine two columns of text in dataframe in pandas/python

以下是我使用的代码。

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()

1 个答案:

答案 0 :(得分:1)

您需要做的就是添加+' /'你加入的两个字符串之间的+。

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

对于你的第二个问题,你可以运行df [" PHASE"]。dtype并分享该系列的数据类型是什么?如果它是一个字符串,那么excel中的任何内容都将被完全复制。一种可能的解决方案是首先将其显式转换为整数:

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

希望有所帮助。