【发布时间】:2018-01-26 14:55:24
【问题描述】:
这是我的工作代码,它正在从网站下载一个 excel 文件。大约需要 40 秒。
运行此代码后,您会注意到 Key1、Key2 和 Key3 列是对象 dtype。我清理了数据框,使 key1 和 key2 只有字母数字值。熊猫仍然将其保留为对象 dtype。我需要连接(如在 MS Excel 中)Key1 和 Key2 以创建一个名为 deviceid 的单独列。我意识到我不能加入这两列,因为它们是对象 dtypes。如何转换为字符串以便创建新列?
import pandas as pd
import urllib.request
import time
start=time.time()
url="https://www.misoenergy.org/Library/Repository/Market%20Reports/20170816_da_bcsf.xls"
cnstsfxls = urllib.request.urlopen(url)
xlsf = pd.ExcelFile(cnstsfxls)
dfsf = xlsf.parse("Sheet1",skiprows=3)
dfsf.drop(dfsf.index[len(dfsf)-1],inplace=True)
dfsf.drop(dfsf[dfsf['Device Type'] == 'UN'].index, inplace=True)
dfsf.drop(dfsf[dfsf['Device Type'] == 'UNKNOWN'].index, inplace=True)
dfsf.drop(['Constraint Name','Contingency Name', 'Constraint Type','Flowgate Name'],axis=1, inplace=True)
end=time.time()
print("The entire process took - ", end-start, " seconds.")
【问题讨论】:
-
你试过了吗:
df[['key1', 'key2', 'key3']].astype(str)? -
我试过这个....a=dfsf.Key1.astype(str) 并且仍然保留 a as 对象。不明白为什么它持有对象类型。
-
您的列中可能有混合类型...
-
有办法检查吗?
-
或者您知道如何遍历 Key1 的每个单元格并尝试转换为 str 吗?
标签: python pandas type-conversion