我是 Python/Pandas 的新手,我正在使用 Spyder IDF,通过 Anaconda 发行版和 Python 3.6(也许是 3.7?)。我正在通过下面的代码导入一个 Excel 文件,想知道如何获得一个输出如下:
伏/相
目前,Excel 中的输出格式如下:
VOLTS.PHASE.0
(此外,我调用的第二列 - PHASE 是一位数。但是,它将它导出为两位数。一个常见的例子是它调用 1 但返回 01。这与假设 float 的 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()
最佳答案
您需要做的就是在要连接的两个字符串之间添加 + '/' +。
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)
希望对您有所帮助。
关于python - 在 Pandas/Python 中格式化连接的列。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46568626/