我正在使用Python在PANDAS工作,我正在查看天气CSV文件。我可以毫无问题地从中提取数据。但是,我无法提取符合某些标准的数据,例如何时显示温度高于100度的天数。
到目前为止,我已将此作为我的代码:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
df = pd.read_csv('csv/weather.csv')
print(df[[df.MaxTemperatureF > 100 ]])
最后一行是我认为我有问题的地方。在执行以下步骤后,我现在获得的错误回溯如下:
Traceback (most recent call last):
File "weather.py", line 40, in <module>
print(df[df['MaxTemperatureF' > 100]])
TypeError: unorderable types: str() > int()
Mikes-MBP-2:dataframes mikecuddy$ python3 weather.py
Traceback (most recent call last):
File "weather.py", line 41, in <module>
print(df[[df.MaxTemperatureF > 100 ]])
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-
packages/pandas/core/frame.py", line 1991, in __getitem__
return self._getitem_array(key)
File "/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/site-
packages/pandas/core/frame.py", line 2028, in _getitem_array
(len(key), len(self.index)))
ValueError: Item wrong length 1 instead of 360.
我一直在做一个教程:http://www.gregreda.com/2013/10/26/working-with-pandas-dataframes/再一次任何帮助都会很棒!谢谢!
df.info()信息:
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 360 entries, 0 to 359
Data columns (total 23 columns):
PST 360 non-null object
MaxTemperatureF 359 non-null float64
Mean TemperatureF 359 non-null float64
Min TemperatureF 359 non-null float64
Max Dew PointF 359 non-null float64
MeanDew PointF 359 non-null float64
Min DewpointF 359 non-null float64
Max Humidity 359 non-null float64
Mean Humidity 359 non-null float64
Min Humidity 359 non-null float64
Max Sea Level PressureIn 359 non-null float64
Mean Sea Level PressureIn 359 non-null float64
Min Sea Level PressureIn 359 non-null float64
Max VisibilityMiles 355 non-null float64
Mean VisibilityMiles 355 non-null float64
Min VisibilityMiles 355 non-null float64
Max Wind SpeedMPH 359 non-null float64
Mean Wind SpeedMPH 359 non-null float64
Max Gust SpeedMPH 211 non-null float64
PrecipitationIn 360 non-null float64
CloudCover 343 non-null float64
Events 18 non-null object
WindDirDegrees 360 non-null int64
dtypes: float64(20), int64(1), object(2)
memory usage: 64.8+ KB
None
答案 0 :(得分:3)
对于最高温度,您可以指定转换器功能:
df = pd.read_csv('csv/weather.csv', converters={'MaxTemperatureF':float})
修改:正如@ptrj在评论中提到的那样,您可以执行此操作,将np.nan
替换为MaxTemperatureF
列中的字符串值:
df = pd.read_csv('csv/weather.csv',
converters={'MaxTemperatureF':
lambda x: try: return float(x);
except ValueError: return np.nan;})
Edit2:@ ptrj的解决方案,因为他无法在评论中写出来......
def my_conv(x):
try:
return float(x)
except ValueError:
return np.nan
df = pd.read_csv('csv/weather.csv', converters={'MaxTemperatureF': my_conv})
其他事项:
header=0
。cols=...
sep
是&#39;,&#39;所以你不需要指定它。答案 1 :(得分:1)
试试这个:你有'()“而不是[]。
http://staging/phpmyadmin/
注释:
print(df[df.MaxTemperatureF.astype(float) > 100 ])