ValueError: could not convert string to float: '6/29/2006' - python-3.x

My code is as follows:
First I create a zero matrix:
ww = (64,8)
tt14=np.zeros(ww)
This is a float matrix. When I want to assign a string value (Date) to the matrix, it gives me this error:
ValueError: could not convert string to float: '6/29/2006'
Where is the problem?

The matrix expects Float types and the date is a type of String. You can convert the date to float by converting it into a timestamp first:
import time
date_str = "6/29/2006"
time_tuple = time.strptime(date_str, "%m/%d/%Y")
timestamp = time.mktime(time_tuple)
Result print timestamp:
1151503200.0
On retrieval we can convert the timestamp back to string:
dt_obj = datetime.fromtimestamp(timestamp)
date_str = dt_obj.strftime("%m/%d/%Y")
Result print date_str:
06/29/2006
Or as pointed out in the comments
If the array is only used for string values you can pass a data type parameter to numpy.zeros() to populate the matrix with empty strings:
ww = (64,8)
tt14=np.zeros(ww, dtype = str)
Now you can add any string value to the matrix.

Related

How to covert different datatypes in single column to integer in python?

I want to convert different datatypes in age column to integer type as we can see the string, Na, and numeric type.
I tried the below code but isn't worked
train['age'].unique()
train.age =train.age.str.replace(' ', '')
Use:
#converting to numeric
train.age = pd.to_numeric(train.age.str.strip(), errors='coerce')
#remove non numeric values
train = train.dropna(subset=['age'])
#convert to integers
train.age = train.age.astype(int)

Python split currency string into currency code and amount

I am trying to split R15.49 to (R, 15.49) or
ZAR15.49 to (ZAR, 15.49)
I have tried one of the solutions here and implememted the function below:
def splitCurrency(string):
match = re.search(r'([\D]+)([\d,]+)', string)
output = (match.group(1), match.group(2).replace(',',''))
return output
But I am getting (R, 15) or (ZAR, 15). and its ignoring the digits after the decimal place
If you want to fish out these values from a larger text, then use re.findall:
inp = "R15.49 or ZAR15.49"
matches = re.findall(r'\b([A-Z]+)(\d+(?:\.\d+)?)\b', inp)
print(matches)
This prints:
[('R', '15.49'), ('ZAR', '15.49')]

How can I concatenate and integer with a string?

I'm receiving an error when I try to concatenate weight_kg with a string "kilograms". I want the numerical output of weight_kg followed by the string "kilograms". E.g. '50 kilograms'.
I've tried to convert weight_kg as a string so I can concatenate it to the string "kilograms"
weight_lbs = input("Weight (lbs): ")
weight_kg = int(weight_lbs) * 0.45
print(weight_kg)
print(weight_kg) + str("kilograms")
TypeError: unsupported operand type(s) for +: 'NoneType' and 'str'
print(weight_kg) + str("kilograms")
you were trying to add the return value of a print() (which is a NoneType) to a string. They can't be added together.
You might want something like this:
print( str(weight_kg) + "kilograms" )
which converts weight_kg to string first then concatenates and prints the result out.
Try this:
print(str(weight_kg)+"kilograms")
no need to cast a string again to string,
and use str(object) to case object to str (like integer at your case)
and print function syntax is print("things to be printed <must be inside the () of the print func>")
to concatenate a 2 strings just str3=str_1+str_2
so according to this all :
print(str(weight_kg)+"kilograms")

How to convert a string value in dataframe to float

I have a csv file and I have to clean data.The problem is that I can fill the empty values by df.fillna() but there are some continious numbers in string which needs to be converted to float or int for further calculations.
I tried couple of methods but cannot find a solution.
Kindly help as I am new in data science field and maybe have made some mistake asking the question.
This column has an string value : df['hum'][316] = '64.70'
type(df['hum'][316]) = str
I stored the string value to a variable and then used float(value) but it gives an error.
value = df['hum'][316]
>>>' "64.70"'
type(value)
>>> str
float(value)
>>>ValueError: could not convert string to float: ' "64.70"'
ValueError: could not convert string to float: ' "64.70"'
df['hum'][316] = float(df['hum'][316])
seems the problems is the " inside the string, remove it by using a regular expression
import re
value = df['hum'][316]
value=re.sub('"','',value)
float(value)
instead of float possible to check also astype for cast operations applying on the whole df or series (column)
if you want to change the whole column of df to a float try:
df['hum'] = df['hum'].str.replace('"', '')
df['hum']=df['hum'].astype('float')
regards giulio

MATLAB: Concatenate number value as string

I want to create a binary number in matlab and am having difficulty concatenating the numbers.
Here's what I tried so far:
testarray = zeros(10,10)
testarray = num2str(testarray) % Convert all values to type string
testarray(1,1) = num2str(1); % Fill with abitrary value
testarray(1,1) = strcat(testarray(1,1), num2str(0)); % Trying to make '10' here but instead I get this error: "Assignment has more non-singleton rhs dimensions than non-singleton subscripts"
Any help would be appreciated.
In your example, the problem is that '10' has size [1,2], but testarray(1,1) has size [1,1]. So you might consider using cells instead:
testarray = cell(5,5);
testarray{1,1} = strcat(testarray(1,1), num2str(0));
By the way, you should have a look at the function dec2bin.
From the documentation:
dec2bin(23)
ans =
10111
The resulting value is a string.
So if you want to concatenate two binary values (encoded as strings), just do:
['10' '11']
ans =
1011

Resources