【问题标题】:Pandas converting dtype object to stringPandas 将 dtype 对象转换为字符串
【发布时间】:2014-04-03 09:18:28
【问题描述】:

我无法转换列的数据类型。我正在从 yahoo Finance 加载一个 csv 文件。

dt = pd.read_csv('data/Tesla.csv')

这给了我以下信息:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 923 entries, 0 to 922
Data columns (total 7 columns):
Date         923 non-null object
Open         923 non-null float64
High         923 non-null float64
Low          923 non-null float64
Close        923 non-null float64
Volume       923 non-null int64
Adj Close    923 non-null float64
dtypes: float64(5), int64(1), object(1)

我尝试将日期转换为字符串,但无论我尝试什么都不起作用。我试图遍历该行并用 str() 转换它。我尝试使用 dt['Date'].apply(str) 更改对象的 dtype,并且我尝试了一个特殊的 dtype 对象并使用它:

types={'Date':'str','Open':'float','High':'float','Low':'float','Close':'float','Volume':'int','Adj Close':'float'}
 dt = pd.read_csv('data/Tesla.csv', dtype=types)

但似乎没有任何效果。

我使用的是熊猫版本 0.13.1

【问题讨论】:

  • object dtype 如何表示可变长度字符串。你到底想做什么?
  • 我想将数据框中的日期与输入字段给出的日期进行比较,这是一个字符串。我需要将两者进行比较,以便为用户提供正确的信息。

标签: python pandas


【解决方案1】:

将您的日期转换为 DateTime 可以让您轻松地将用户输入的日期与数据中的日期进行比较。

#Load in the data
dt = pd.read_csv('data/Tesla.csv')

#Change the 'Date' column into DateTime
dt['Date']=pd.to_datetime(dt['Date'])

#Find a Date using strings
np.where(dt['Date']=='2014-02-28')
#returns     (array([0]),)

np.where(dt['Date']=='2014-02-21')
#returns (array([5]),)

#To get the entire row's information
index = np.where(dt['Date']=='2014-02-21')[0][0]
dt.iloc[index]

#returns:
Date         2014-02-21 00:00:00
Open                      211.64
High                      213.98
Low                       209.19
Close                      209.6
Volume                   7818800
Adj Close                  209.6
Name: 5, dtype: object

所以如果你想做一个 for 循环,你可以创建一个日期列表或 numpy 数组,然后遍历它们,用你的值替换索引中的日期:

input = np.array(['2014-02-21','2014-02-28'])
for i in input:
    index = np.where(dt['Date']==i)[0][0]
    dt.iloc[index]

【讨论】:

  • 数据可以在这里找到link
  • 数据可以在这里找到 link 我用 pd.to_datetime() 转换了 Date 列,以便循环我使用的行:for i in range(len(tesla),5) : print type((tesla.iloc[[i]]['Date'])) 这给了我一个类型的变量: 我还将字符串转换为日期时间: datetime .strptime('2013-08-20', '%Y-%M-%d') 这给了我 现在我需要将转换后的字符串与 for 循环中的值进行比较。
  • 我越来越近了,我只想获取该特定行中的所有信息。这就是为什么在 for 循环中使用 tesla.iloc[[i]]['Date'] 的原因。
猜你喜欢
  • 2014-03-17
  • 1970-01-01
  • 2020-08-27
  • 2017-09-15
  • 1970-01-01
  • 2016-03-01
  • 2023-03-09
  • 2014-07-25
  • 2021-12-07
相关资源
最近更新 更多