'NoneType' object has no attribute 'fileno' - python

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from datetime import datetime
plt.style.use('ggplot')
columns = ['user_id','order_dt','order_products','order_amount']
df = pd.read_csv('CDNOW_master.txt',names = columns,sep = '\s+')
df['order_date'] = pd.to_datetime(df.order_dt,format='%Y%m%d')
df['month'] = df.order_date.values.astype('datetime64[M]')
f = df.groupby('user_id')['month'].min().value_counts()
print(f)
Above is my code,my purpose is to get the value_counts of the users purchased in their first month, but only got the result of 'NoneType' object has no attribute 'fileno'.
any ideas? much appreciate
here are the traceback
Traceback (most recent call last):
File "C:\Users\Administrator\Desktop\practice\CDNOW.py", line 19, in <module>
print(f)
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas\core\base.py", line 51, in __str__
return self.__unicode__()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas\core\series.py", line 982, in __unicode__
width, height = get_terminal_size()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\site-packages\pandas\io\formats\terminal.py", line 33, in get_terminal_size
return shutil.get_terminal_size()
File "C:\Users\Administrator\AppData\Local\Programs\Python\Python35\lib\shutil.py", line 1071, in get_terminal_size
size = os.get_terminal_size(sys.__stdout__.fileno())
AttributeError: 'NoneType' object has no attribute 'fileno'

I am seeing this as well.
>>> type(sys.__stdout__)
<class 'NoneType'>
I get NoneType when calling dunder stdout while I am using idle. I assume that pandas wants to determine how much to display in the results and is looking for the sys output information. In the documentation, it mentions what this is, but not how to reset it.
I did this:
sys.__stdout__ = sys.stdout
and it fixed the problem, but I have not idea if I caused problems down the line.

You may wish to try out the following.
df = pd.read_csv('CDNOW_master.txt',usecols = columns,sep = '\s+')
instead of
df = pd.read_csv('CDNOW_master.txt',names = columns,sep = '\s+')
This solved my problem. Hope it solves yours too.

Related

TypeError: 'float' object is not iterable when calling from a function

I want to use the reactome2py package to analyse pathways by adapting the Reference code. Unlike the reference code, which only read one file, my code intends to apply the reactome2py's analysis function for three files, mrna, cna, and meth.
Reference code:
https://colab.research.google.com/drive/1OufIYapCWirfLsudpg0fw1OxD7KTud2y?usp=sharing#scrollTo=e1q6oxLUKGGR
The portion of the code that's throwing the error:
for k, v in chain.from_iterable(cna_dict_items):
cna_dd[k].extend(v)
Full code:
import pandas as pd
import numpy as np
from sklearn.decomposition import PCA
from operator import methodcaller
from itertools import chain
from collections import defaultdict
from reactome2py import analysis
directory = "./gbm_tcga/"
def genepath(cna_row_dict):
cna_dd = defaultdict(list)
cna_dict_items = map(methodcaller("items"), cna_row_dict)
for k, v in chain.from_iterable(cna_dict_items):
cna_dd[k].extend(v)
cna_dict = dict(cna_dd)
return cna_dict
class DataProcessing:
def __init__(self, data):
self.df = pd.read_csv(data, sep="\t", header=0)
def data_dict(self):
df_dict = self.df.to_dict("records")
return df_dict
def main():
cna = DataProcessing(directory + "data_linear_cna.txt")
cna_dict = cna.data_dict()
gene_path = genepath(cna_dict)
main()
Traceback:
Traceback (most recent call last):
File "main.py", line 45, in <module>
main()
File "main.py", line 41, in main
gene_path = genepath(cna_dict)
File "main.py", line 19, in genepath
cna_dd[k].extend(v)
TypeError: 'float' object is not iterable

How to save <class "ctypes.c_char_Array> with pickle

I'm doing research on palmprint recognition. for that I use the edcc library for the introduction of the palmprint. but i have problem in saving the encoding result from palm. I want to save the encoding result into a file, but I get an error like below
Traceback (most recent call last):
File "/home/pi/Coba/PalmDetection/PalmRecognition.py", line 18, in <module>
pickle.dump(one_palmprint_code, config_dictionary_file)
_pickle.PicklingError: Can't pickle <class 'ctypes.c_char_Array_849'>: attribute lookup c_char_Array_849 on ctypes failed
My code like this :
import os
import edcc
import cv2
import pickle
TEST_PALMPRINT_DATA_DIR = "/home/pi/Coba/PalmDetection/Data"
TEST_A_01_PALMPRINT_IMAGE = os.path.join(TEST_PALMPRINT_DATA_DIR, "Palm1.jpeg")
#TEST_A_02_PALMPRINT_IMAGE = os.path.join(TEST_PALMPRINT_DATA_DIR, "a_02.bmp")
TEST_B_01_PALMPRINT_IMAGE = os.path.join(TEST_PALMPRINT_DATA_DIR, "palme.jpeg")
#TEST_B_02_PALMPRINT_IMAGE = os.path.join(TEST_PALMPRINT_DATA_DIR, "b_02.bmp")
if __name__ == "__main__":
config = edcc.EncoderConfig(29, 5, 5, 10)
encoder = edcc.create_encoder(config)
one_palmprint_code = encoder.encode_using_file(TEST_A_01_PALMPRINT_IMAGE)
with open('encode.encode', 'wb') as config_dictionary_file:
pickle.dump(one_palmprint_code, config_dictionary_file)
another_palmprint_code = encoder.encode_using_file(TEST_B_01_PALMPRINT_IMAGE)
similarity_score = one_palmprint_code.compare_to(another_palmprint_code)
print(
"{} <-> {} similarity score:{}".format(
TEST_A_01_PALMPRINT_IMAGE, TEST_B_01_PALMPRINT_IMAGE, similarity_score
)
)
What should i do?
The edcc module must use ctypes internally, but really should hide that fact instead of returning a ctypes-wrapped object. A ctypes.c_char_Array_849 is just a C-compatible wrapper around an array of bytes. You can access the equivalent Python bytes object via the .raw property (what edcc should return instead) and write that to the file:
import ctypes
import pickle
one_palmprint_code = (ctypes.c_char * 849)()
with open('encode.encode', 'wb') as config_dictionary_file:
#pickle.dump(one_palmprint_code, config_dictionary_file) # reproduces error
config_dictionary_file.write(one_palmprint_code.raw)

Basemap scatterplot (Matplotlib) - Error can't set attribute

I have been trying to add two lists of floats to a scatterplot using the Matplotlib. I have simply created a Basemap with mostly default settings. However, whenever I attempt to run the script I get the error below.
#!/usr/bin/python
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
def main():
wmap = Basemap()
wmap.drawmapboundary(fill_color='aqua')
wmap.fillcontinents(color='coral',lake_color='aqua')
wmap.drawcoastlines()
locationData = open("locationData", "r")
lats = []
lons = []
ASN = []
company = []
fileLine = locationData.readlines()
for i in fileLine:
parsedLine = i.split(",")
lats.append(float(parsedLine[0]))
lons.append(float(parsedLine[1]))
ASN.append(parsedLine[2])
company.append(parsedLine[3])
locationData.close()
x,y = wmap(lats,lons)
wmap.scatter(x,y)
plt.show()
if(__name__ == '__main__'):
main()
I receive the error:
Traceback (most recent call last):
File "mapGen.py", line 51, in <module>
main()
File "mapGen.py", line 45, in main
wmap.scatter(lats,lons)
File "/usr/lib/python3.7/site-packages /mpl_toolkits/basemap/__init__.py", line 563, in with_transform
return plotfunc(self,x,y,*args,**kwargs)
File "/usr/lib/python3.7/site-packages/mpl_toolkits/basemap/__init__.py", line 3253, in scatter
self._restore_hold(ax)
File "/usr/lib/python3.7/site-packages/mpl_toolkits/basemap/__init__.py", line 3229, in _restore_hold
ax._hold = self._tmp_hold
AttributeError: can't set attribute
I have tried changing around the attributes to wmap.scatter() and the variables, but there error still persists and I haven't been able to find documentation on this error. Any ideas?
This specific exception is raised when the attribute you're trying to change is a property that doesn't have a setter. It seems the basemap change is needed, adding a setter would solve the issue.
But you can change wmap.scatter(x,y) to plt.scatter(x, y) to solve it.

AttributeError: 'Point' object has no attribute 'point'

I am transforming a point from source frame to target frame using tf2. Below is the code snippet:
import tf2_ros
import tf2_geometry_msgs
transform = tf_buffer.lookup_transform(target_frame, source_frame, rospy.Time(0), rospy.Duration(1.0))
pose_transformed = tf2_geometry_msgs.do_transform_point(point_wrt_kinect, transform)
print pose_transformed
The code throws following error:
Traceback (most recent call last):
File "q1.py", line 29, in <module>
pose_transformed = tf2_geometry_msgs.do_transform_point(point_wrt_kinect, transform)
File "/opt/ros/indigo/lib/python2.7/dist-packages/tf2_geometry_msgs/tf2_geometry_msgs.py", line 59, in do_transform_point
p = transform_to_kdl(transform) * PyKDL.Vector(point.point.x, point.point.y, point.point.z)
AttributeError: 'Point' object has no attribute 'point'
The tf_geometry_msgs.py can be seen online at here. This seems silly as they are calling point.point.x.
Which point are they talking about? I believe it should be geometry_msgs/Point, which I declared in the following way:
from geometry_msgs.msg import Point
point_wrt_kinect = Point()
point_wrt_kinect.x = -0.41
point_wrt_kinect.y = -0.13
point_wrt_kinect.z = 0.77
Any workaround, please?
do_transform_point(point_wrt_kinect, transform)
point_wrt_kinect is the object of Point class. In documentation it should be PointStamped class object. its the error of documentation.
you have to create object of PointStamped class instead of Point class.

Python - an identical line of code using datetime fails in one file but not another

I have the following lines of code in project A
#filename : mod_dates
#Handles date calculations etc
import datetime
class datecalcs:
def __init__(self):
self.__menuChoice = 0
self.__datemonth = "not set"
self.__effectivedate = ""
self.__year = 0
self.__month = 0
return None
#
def interestcouponpaydates(self,effectivedate,couponday):
self.__effectivedate = effectivedate
year, month, day = map(int,self.__effectivedate.split('-'))
print(year)
print(month)
return self.__effectivedate
When I call them from another file with
import mod_dates
import datetime
import modcalinputs
datesclass = mod_dates.datecalcs()
calcInputs = modcalinputs.calcinputs()
#Get the coupon date
interestdateeffective = calcInputs.interestdateffective()
interestdatecoupon = calcInputs.interestdatecoupon()
x = datesclass.interestcouponpaydates(interestdateeffective,interestdatecoupon)
print(x)
However this returns an error on the x = datesclass... line of
year, month, day = map(int,self.__effectivedate.split('-'))
raises:
> AttributeError: 'datetime.date' object has no attribute 'split'
When I run from a similar project to the same line with the same syntax it works fine. Any ideas on what I am doing wrong?
Looks like something is assigning a datetime.date object to __effectivedate. You can't call split() on that:
>>> import date
>>> d = d = datetime.date(2012,3,12)
>>> d.split('-')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'datetime.date' object has no attribute 'split'
You can convert it to a string and split:
>>>str(d).split('-')
['2012', '03', '12']

Categories

Resources