我从sql查询(2014年5月到2015年6月的数据)构建一个数据帧,并尝试构建两个不同的数据集-训练使用除2015年6月之外的所有数据-当我尝试使用时,测试只使用2015年6月的数据: train= df(df.month!=6) & (df.year!= 2015 )
似乎我使用的是OR而不是AND,因为我没有得到month=6的任何值(2014年也没有),也没有year=2015的值,所以2015年的其他月份也没有。
我不明白代码出了什么问题。
mycurs.execute("""SELECT day, month, year, cloudcover, moonphase, precipintensity,
precipaccumulation, preciptype2, humidity, pressure, windspeed,
uvindex, visibility, temperaturehigh, weekend_2, crimecount
FROM open.nyc_weatherhist_2""")
f=mycurs.fetchall() #returns tuple with first row (unordered list)
df=pd.DataFrame(f, columns=feature_names)
print(df) day month year ... temperaturehigh weekend crimecount
0 28 4 2015 ... 20.85 0 56
1 14 4 2015 ... 18.25 0 103
2 13 7 2014 ... 27.44 0 89
3 4 1 2015 ... 12.94 0 99
4 21 9 2014 ... 24.15 0 66
.. ... ... ... ... ... ... ...
390 4 7 2014 ... 23.37 1 84
391 8 8 2014 ... 27.98 1 97
392 26 4 2015 ... 15.78 0 82
393 3 8 2014 ... 24.50 0 80
394 5 6 2015 ... 20.65 1 87
[395 rows x 16 columns]train= df[(df.month!=6) & (df.year!=2015)]
print(train) day month year ... temperaturehigh weekend crimecount
2 13 7 2014 ... 27.44 0 89
4 21 9 2014 ... 24.15 0 66
8 10 11 2014 ... 16.27 0 76
9 5 11 2014 ... 17.76 0 101
11 10 7 2014 ... 28.06 0 99
.. ... ... ... ... ... ... ...
382 10 8 2014 ... 30.51 0 119
389 21 11 2014 ... 2.65 1 110
390 4 7 2014 ... 23.37 1 84
391 8 8 2014 ... 27.98 1 97
393 3 8 2014 ... 24.50 0 80
[184 rows x 16 columns]发布于 2020-03-31 17:45:34
只是在阐述弗朗西斯的答案,你以错误的方式看待这种情况。
您想要除特定年份的特定月份之外的所有数据。那么,什么时候这个值是“正确的”呢?如果它们中的任何一个不在月份或年份。
所以,这就是OR条件。
另一种看待它的方式--你有条件X和Y。如果X和Y都存在,或者只是X & Y,那么你就错了。
那么,你什么时候是“正确的”?When !(X & Y) == !X | !Y.
如何处理这个问题是你的选择,但你可以这样做:
train = df[(df.month != 6) | (df.year != 2015)]
或
train = df[~((df.month == 6) & (df.year == 2015))]
它们是等价的
发布于 2020-03-31 17:32:50
您需要根据需要使用| for OR。
>>> df = pd.DataFrame({'year':[2014,2015,2015],'month':[6,5,6]})
>>> df
year month
0 2014 6
1 2015 5
2 2015 6
>>> train = df[(df['year']!=2015) | (df['month']!=6)]
>>> train
year month
0 2014 6
1 2015 5https://stackoverflow.com/questions/60947264
复制相似问题