2017-04-05 69 views
2

我正在蟒蛇/熊猫可能很容易的东西...函数列Python

我有一个数据帧与列日期,索引水果名称和内部价格。

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

[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 

非常感谢!

编辑:我的目标是进入一个日期,这让我回coresponding列,因此 日期=“2017年3月23日” myPrice(日期) 返回相应。

所以我不会试图通过MYLIST [2017年3月23日],但东西谁应该MYLIST [日期]

回答

3

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

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]) 
+0

感谢您的回复,但我希望通过在函数中输入日期。 像 Myprice(日期) 日期= '2017年3月23日' 然后返回相应的列 – user6457870

+0

然后只限定'myPrice =拉姆达日期:mylist.loc [:,日期]' – Quickbeam2k1

+0

它给回<函数__主要__。 > – user6457870

3

pandas允许你通过列名访问列与[]选择

mylist['2017-03-23'] 

但是,为了更加明确,你可以使用.loc[]

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

甚至使用xs方法:

mylist.xs('2017-03-23', axis=1) 

上述任何一个可以被包裹在一个功用:

def myPrice(date): 
    return mylist[date] 
+0

谢谢您的COMENT,不幸的是,当我这样做,它返回 TypeError:只有一个元素的整数数组可以转换为索引 – user6457870

+0

@ user6457870对不起,有一个错字。我在函数中使用'data'而不是'date'。再试一次 – piRSquared

+0

我知道我已经修改了它,它仍然会给出错误... – user6457870