python – pandas:用loc迭代DataFrame索引
我似乎无法找到.loc行为背后的原因.我知道它是基于标签的,所以如果我遍历Index对象,下面的最小例子应该可行.但事实并非如此.我当然用Google搜索,但我需要一些已经掌握索引的人的其他解释. import datetime import pandas as pd dict_weekday = {1: 'MON',2: 'TUE',3: 'WED',4: 'THU',5: 'FRI',6: 'SAT',7: 'SUN'} df = pd.DataFrame(pd.date_range(datetime.date(2014,1,1),datetime.date(2014,15),freq='D'),columns=['Date']) df['Weekday'] = df['Date'].apply(lambda x: dict_weekday[x.isoweekday()]) for idx in df.index: print df.loc[idx,'Weekday'] 解决方法问题不在于df.loc;df.loc [idx,’Weekday’]刚刚返回一个系列. 令人惊讶的行为是由于pd.Series尝试将类似日期时间的值转换为Timestamps的方式. df.loc[0,'Weekday'] 形成系列 pd.Series(np.array([pd.Timestamp('2014-01-01 00:00:00'),'WED'],dtype=object)) 当调用pd.Series(…)时,它将tries to cast the data转换为适当的dtype. 如果您浏览代码,您会发现它最终到达these lines in pandas.core.common._possibly_infer_to_datetimelike: sample = v[:min(3,len(v))] inferred_type = lib.infer_dtype(sample) 这是检查数据的前几个元素并尝试推断dtype. In [138]: pd.Timestamp('Wed') Out[138]: Timestamp('2014-12-17 00:00:00') 这是问题的根源,导致pd.Series返回 In [139]: pd.Series(np.array([pd.Timestamp('2014-01-01 00:00:00'),dtype=object)) Out[139]: 0 2014-01-01 1 2014-12-17 dtype: datetime64[ns] 因此返回 In [140]: df.loc[0,'Weekday'] Out[140]: Timestamp('2014-12-17 00:00:00') 而不是’星期三’. 替代方案:首先选择系列df [‘Weekday’]: 有很多解决方法; EdChum表明,向样本添加非日期(整数)值可以防止pd.Series将所有值强制转换为时间戳. 或者,您可以在使用.loc之前访问df [‘Weekdays’]: for idx in df.index: print df['Weekday'].loc[idx] 替代方案:df.loc [[idx],’Weekday’]: 另一种选择是 for idx in df.index: print df.loc[[idx],'Weekday'].item() df.loc [[idx],’Weekday’]首先选择DataFrame df.loc [[idx]].例如,当idx等于0时, In [10]: df.loc[[0]] Out[10]: Date Weekday 0 2014-01-01 WED 而df.loc [0]返回系列: In [11]: df.loc[0] Out[11]: Date 2014-01-01 Weekday 2014-12-17 Name: 0,dtype: datetime64[ns] Series尝试将值转换为单个有用的dtype. DataFrame可以为每列提供不同的dtype.因此,Date列中的Timestamp不会影响Weekday列中值的dtype. 因此,使用返回DataFrame的索引选择器可以避免问题. 替代方案:使用整数作为工作日 另一种方法是在工作日存储isoweekday整数,并在打印时仅在结尾处转换为字符串: import datetime import pandas as pd dict_weekday = {1: 'MON',columns=['Date']) df['Weekday'] = df['Date'].dt.weekday+1 # add 1 for isoweekday for idx in df.index: print dict_weekday[df.loc[idx,'Weekday']] 替代方案:使用df.ix: df.loc是_LocIndexer,而df.ix是_IXIndexer.他们有 def __getitem__(self,key): if type(key) is tuple: try: values = self.obj.get_value(*key) 并且DataFrame方法df.get_value成功返回’WED’: In [14]: df.get_value(0,'Weekday') Out[14]: 'WED' 这就是为什么df.ix是另一种在这里工作的选择. (编辑:十堰站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- 使用python中的csv模块写入特定单元格
- python的vim设置
- python – Pandas concat:ValueError:传递值的形状是blah
- python – 编写一个通用的getattr()并根据attr名称填充方法
- python – 来自Windows的OpenCV构建错误“RC对象”
- python – Django 1.7 makemigrations – ValueError:无法
- python – matplotlib.pyplot.imshow:在使用属性“sharex”
- python – 带有runserver的Unicodedecodeerror
- 如何为Python 3安装bpython?
- Python可以生成类似于bash的set -x的跟踪吗?
- python – Aiohttp,Asyncio:RuntimeError:事件
- python – 了解matplotlib xticks语法
- Python使用urllib2模块实现断点续传下载的方法
- python – gcloud.exceptions.Forbidden:403权限
- Python:如何找到使用matplotlib绘制的图形的斜率
- 什么是Perlbrew的Python等价物?
- 在IPython中使用Interactive Shell之外的魔术命令
- python – Mac OS上“import cv”期间的“分段错
- python – 从字符串列表中分离的字符串创建字典
- Python使用metaclass实现Singleton模式的方法