gpt4 book ai didi

python - Pandas 数据框无法将列数据类型从对象转换为字符串以进行进一步操作

转载 作者:太空狗 更新时间:2023-10-30 01:36:41 25 4
gpt4 key购买 nike

这是我的工作代码,它正在从网站下载一个 excel 文件。大约需要 40 秒。

运行此代码后,您会注意到 Key1、Key2 和 Key3 列是对象数据类型。我清理了数据框,使 key1 和 key2 只有字母数字值。 Pandas 仍然将其保留为对象数据类型。我需要连接(如在 MS Excel 中)Key1 和 Key2 以创建一个名为 deviceid 的单独列。我意识到我不能加入这两列,因为它们是对象数据类型。我如何转换为字符串以便创建新列?

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.")

最佳答案

我可能忽略了这里的重点。但是如果你想做的是构建一个列,例如,当 Key1 = RCHKey2 = 417 时,deviceid = RCH417,那么即使两列都是对象类型,dfsf['deviceid'] = dfsf['Key1'] + dfsf['Key2'] 也能正常工作。

试试这个:

# Check value types
dfsf.dtypes

# Add your desired column
dfsf['deviceid'] = dfsf['Key1'] + dfsf['Key2']

# Inspect columns of interest
keep = ['Key1', 'Key2', 'deviceid']
df_keys = dfsf[keep]
print(df_keys.dtypes)

enter image description here

print(df_keys.head())

enter image description here

关于python - Pandas 数据框无法将列数据类型从对象转换为字符串以进行进一步操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45747866/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com