python - 函数列 Python

标签 python python-2.7 pandas dataframe sklearn-pandas

我正在为一些在 python/pandas 中可能很简单的事情而苦苦挣扎......

我有一个数据框,其中包含日期列、索引水果名称和内部价格。

我正在寻找一个函数,当我输入一个日期时,它会给我该日期的水果价格。

[in]  mylist
[out]

             2017-03-23 2017-03-22 2017-03-21 2017-03-20 2017-03-17 2017-03-16 

pear            12       13        14        12        20      17   
apple           14        9        11        21        12      4   
banana         120       180       140       170       605     802  
etc...         NaN       NaN       NaN       NaN       NaN     NaN   


ex. [in] myPrice('2017-03-23')
[out]   2017-03-23
pear       12
apple      14 
banana     120

非常感谢!

编辑:我的目标是输入一个日期,它会返回相应的列,所以 日期 = '2017-03-23' 我的价格(日期) 返回相应的。

所以我不是想通过 mylist[2017-03-23] 来做,而是用一些应该是 mylist[date] 的人

最佳答案

如果列是字符串,我认为你需要:

mylist['2017-03-23']
mylist.loc[:, '2017-03-23']

如果列是日期时间,则需要 datetime:

#If columns not datetime, convert them
mylist.columns = pd.to_datetime(mylist.columns)

#convert string to datetime
date = pd.to_datetime('2017-03-23')
#another solution
#date = pd.Timestamp('2017-03-23')

print (mylist[date])
pear       12
apple      14
banana    120
Name: 2017-03-23 00:00:00, dtype: int64

print (mylist.loc[:, date])
pear       12
apple      14
banana    120
Name: 2017-03-23 00:00:00, dtype: int64

对于一列 DataFrame 添加 []:

print (mylist[[date]])
        2017-03-23
pear            12
apple           14
banana         120

print (mylist.loc[:, [date]])
        2017-03-23
pear            12
apple           14
banana         120

也有效(但我收到警告):

VisibleDeprecationWarning: converting an array with ndim > 0 to an index will result in an error in the future block = self.blocks[self._blknos[i]]

date ='2017-03-23'
print (mylist[date])

关于python - 函数列 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43224900/

相关文章:

python - 使用 get_dummies 时删除冗余列

python - 我如何记住 list.append 和 list.extend 中的哪一个是 Python 中的哪一个?

python-2.7 - 在Python 2.7中手动构建ConfigParser的深拷贝

python - 如何正确解析右括号

python - 如何在 try ... except 中捕获异常后继续循环

python - 使用 if 语句遍历列表

python - Python 中 'empty' else 语句的必要性

python-2.7 - Python 2.7.3中的奇怪语法错误

python - 获取 Pandas 中数据帧的子集

Python将数组的值拆分为不同的列