Trying to extract numeric part from column-dtype('O') and have the extracted data in a new column or replace the existing column.
In this process the apply method didnt work for the code below. Provided the traceback also
code
def dpr_size(data_size):
split_size = re.split('(\d*.*\d)', data_size)
size = float(split_size[0])
return float(size)
df1['size_new'] = df1.size.astype('str').apply(dpr_size)
Traceback
AttributeError Traceback (most recent call last)
in ()
5 return float(size)
6
----> 7 df1['size_new'] = df1.size.apply(dpr_size)
AttributeError: 'numpy.int32' object has no attribute 'apply'
Tried many other alternatives, and now the below code works.
code
df1['size'] = df1['size'].astype('str')
for i in range(len(df1['size'])):
split_size = re.split('(\d*.*\d)', df1['size'][i])[1:]
df1['size'][i] = split_size[0]
However want to find out why 'apply' doesnt work
Data
Related
I'm trying to preprocess video frames for anomaly event detection. The model is already trained but I can't figure out the issue with the following code (I'm a beginner). Please help with this respected developers.
def Fit_Preprocessing(path: object, frames_ext: object) -> object:
if frames_ext is None:
raise TypeError(
'Invalid Value for argument `frames_ext`, it cannot be None. Give proper extensions of the frames e.g: `.tif` or `.png` etc!')
print('\n\nProcessing Images in this Dataset Path: {0}\n'.format(path))
file_names: List[Union[str, List[str]]]
onlyfiles, file_names, dirs = ReadFileNames(path, frames_ext)
img_list = [1, 2, 3, 4]
for img in tqdm(range(len(onlyfiles))):
images = onlyfiles[img]
count = 0
for images in onlyfiles[img]:
img.split('/')
img_name = dirs[i] + '_' + file_names[i][count]
write_path = 'ProcessedImages/' + path.split('/')[1]
gray = ProcessImg(img_name, read_path=img, write=True,
write_path=write_path, res_shape=(227, 227))
img_list.append(gray)
count += 1
return img_list
Getting this error:
Processing Images in this Dataset Path: C:/Users/Public/Downloads/Surveillance with deep learning/Datasets/UCSD_Anomaly_Dataset.v1p2/UCSDped1/Test
0%| | 0/47 [00:00<?, ?it/s]
Traceback (most recent call last):
File "C:/Users/Public/Downloads/Surveillance-with-deep-learning/preprocessing.py", line 171, in <module>
img_list: object = Fit_Preprocessing(path, frames_ext='.Fit')
File "C:/Users/Public/Downloads/Surveillance-with-deep-learning/preprocessing.py", line 154, in Fit_Preprocessing
for images in onlyfiles[img]:
TypeError: 'int' object is not iterable
Process finished with exit code 1
I tried using images = img_list to fix the loop but it did not work
The reason you are getting an error is because in the for loop:
for images in onlyfiles[img]:
You are getting the value using the index to access it, and onlyfiles[img] will, according to your code, return an int value. Since I don't know what you are clearly doing, my suggestion is to turn onlyfiles[img] into a list, so it iterates only through one thing or more, using:
for images in [onlyfiles[img]]:
Example:
my_int = 123
for i in my_int:
print(i)
Gets the error:
Traceback (most recent call last):
File "main.py", line 2, in <module>
for i in my_int:
TypeError: 'int' object is not iterable
So if you turn it into a list:
my_int = 123
for i in [my_int]:
print(i)
Gives:
123
Or if you want to iterate through the digits, turn it into a string:
my_int = 123
for i in str(my_int):
print(i)
Gives:
1
2
3
I am trying to save various excel files that are produced in the code below to a specific folder, but keep getting "SyntaxError: invalid syntax".
#df = some random data
dfinvest = df[df['INVEST'] >= 0.1]
groupedinvest = dfinvest.groupby("SEDOL")
keysI = groupedinvest.groups.keys()
save_path = "C:/Users/Documents/Python Scripts/"
for key in keysI:
splitdf = groupedinvest.get_group(key)
splitdf.to_excel(os.path.join(save_path((str(key)+ str(datetime.datetime.now().strftime(" %d-%m-%Y - Invest") )+ ".xlsx"), engine='xlsxwriter')))
Any help or pointing in the right direction would be much appreciated.
Error:
TypeError Traceback (most recent call last)
<ipython-input-48-5616ac4f50b7> in <module>
1 for key in keysI: #looping through each key
2 splitdf = groupedinvest.get_group(key) # creating a temporary dataframe with only the values of the current key.
----> 3 splitdf.to_excel(os.path.join(save_path((str(key)+ str(datetime.datetime.now().strftime(" %d-%m-%Y - Invest") )+ ".xlsx"), engine='xlsxwriter')))
TypeError: 'str' object is not callable
This question already has answers here:
Why do I get AttributeError: 'NoneType' object has no attribute 'something'?
(11 answers)
Closed 1 year ago.
My code:
models = [dtree,bagging,bagging_wt,rf,rf_wt,dtree_estimator,bagging_estimator,rf_estimator]
acc_train = []
acc_test = []
recall_train = []
recall_test = []
precision_train = []
precision_test = []
for model in models:
j = get_accuracy_score(model,False)
acc_train.append(j[0])
acc_test.append(j[1])
k = get_recall_score(model,False)
recall_train.append(k[0])
recall_test.append(k[1])
l = get_precision_score(model,False)
precision_train.append(l[0])
precision_test.append(l[1])
Error:
TypeError Traceback (most recent call last)
<ipython-input-215-b1cbc190be6f> in <module>
12
13 j = get_accuracy_score(model,False)
---> 14 acc_train.append(j[0])
15 acc_test.append(j[1])
16
TypeError: NoneType' object is not subscriptable
You need to familiarize yourself with how Python traceback works.
All the information you need is in the exception itself.
It tells you that the object is not subscriptable in lines 14 and 15. You are trying to access indexes in an object that does not allow it or does not have it (in this case, None).
And as #edusanketdk said, your function get_accuracy_score is at fault here as it returns None rather than a container object.
I am getting the following error on the code below :
Traceback (most recent call last):
File "D:/Personal Files/Technical Development/PycharmProjects/Call Center Headcount Model/Call Center Headcount Model.py", line 12, in
historical_start_date = work_rules.iloc(4, 2)
TypeError: call() takes from 1 to 2 positional arguments but 3 were given
I am trying to assign a cell value in excel to a variable in Python through pandas. i.e. Historical_start_date = work_rules.loc(4,2)
Any idea why this is?
Code:
work_rules = pd.read_excel(
'D:\\Personal Files\\Technical Development\\PycharmProjects\\Call Center Headcount Model\\Call Center Work Rules.xlsx',
sheet_name='Inputs')
historical_start_date = work_rules.iloc(4, 2)
print(historical_start_date)
Please refer to the Iloc documentation. You're supplying variables as if it is a method. I'm not sure what you want to do exactly but it seems to me that you need to replace the parenthesis after iloc with brackets.
I have a dataframe column that has these values in one of its columns:
Jerry
NaN
bill
Sol
I want to catch the all lowercase names, i.e., bill. But my code keeps getting stuck, I think on the NaN.
Here is my code:
for n in df_copy.name:
if n.islower():
print(n)
I get this error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-296-2e5fe579149d> in <module>
1 for n in df_copy.name:
----> 2 if n.islower():
3 print(n)
AttributeError: 'float' object has no attribute 'islower'
So I tried making the values a string:
for n in df_copy.name:
if n.str.islower():
print(n)
It gives me this error:
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-295-7e9d8aa5abad> in <module>
1 for n in df_copy.name:
----> 2 if n.str.islower():
3 print(n)
AttributeError: 'str' object has no attribute 'str
Argh. Does anyone know how to solve this?
We can using str.islower
df[df.name.str.islower().fillna(False)]
Out[243]:
name
2 bill