You can use dt.strftime for formating datetimes and then custom format of floats:
df['time'] = df['time'].dt.strftime('%Y,%m,%d %H:%M:%S')
cols = ['price1','price2']
df[cols] = df[cols].applymap(lambda x: '{0:.4f}'.format(x))
print (df)
time price1 price2
0 2018,02,01 00:00:00 1.4527 1.6548
Answer from jezrael on Stack OverflowYou can use dt.strftime for formating datetimes and then custom format of floats:
df['time'] = df['time'].dt.strftime('%Y,%m,%d %H:%M:%S')
cols = ['price1','price2']
df[cols] = df[cols].applymap(lambda x: '{0:.4f}'.format(x))
print (df)
time price1 price2
0 2018,02,01 00:00:00 1.4527 1.6548
You can use the round method to show only 4 decimals. and use .apply(str) to convert it to string object
EX:
df["price1"] = df["price1"].round(4).apply(str)
df["price2"] = df["price2"].round(4).apply(str)
Convert float to string without losing precision.
Python Pandas Dataframe convert String column to Float while Keeping Precision (decimal places) - Stack Overflow
How I convert float to string in this case?
python - Extract floats from a column of strings and round to 2 decimal places - Stack Overflow
I am looking to manipulate a data frame of floats which all need 6 decimal points after manipulation.
I am looking to add brackets and () around the floats based on conditionals which is why I need to convert to strings. I then can concat the two strings together
However when I convert to str, it reduces the number of decimals to 2.
For example
-35.920000 Original Dataframe
Converted to str
-35.92 After conversion
If I convert the string back to a float, it does not retain the 6 decimals from the original df.
My understanding is both values are stored the same and they both are logically = when checked in the notebook , but for management reasons I am trying to see if there is a way to coerce the string method the take a literal copy of the float, rather than reducing it down.
Sorry for the formatting, I am on mobile .
Thanks
I tried
n1=input('First number')
n2=input('Second number')
sum = float(n1) + float(n2)
str(sum)
print('The sum of the values is: ' + sum)My error is:
TypeError: can only concatenate str (not "float") to str
I tried googling this error and got some answers like print(f' which I didn't really understand, and some others that looked a little complicated, I am very new.
I am trying to improve my googling skills.
print(s)
0 4.5678
1 5
2 7.987.998
Name: 0, dtype: object
print(type(s))
Out[152]: pandas.core.series.Series
Using str.extract + round:
r = s.str.extract('(\d+(?:\.\d+)?)', \
expand=False).astype(float).round(2)
print(r)
0 4.57
1 5.00
2 7.99
Name: 0, dtype: float64
Unfortunately, the 5 cannot be an integer as your expected output describes, that would lead to mixed types and is generally discouraged.
str = "7.987.998"
ind = str.find('.')
if ind > 0:
res = str[:ind+3]
For pandas >= 1.0:
<NA> type was introduced for 'Int64'. You can now do this:
df['your_column'].astype('Int64').astype('str')
And it will properly convert 1.0 to 1.
Alternative:
If you do not want to change the display options of all pandas, @maxymoo solution does, you can use apply:
df['your_column'].apply(lambda x: f'{x:.0f}')
Converting to int (i.e. with .astype(int).astype(str)) won't work if your column contains nulls; it's often a better idea to use string formatting to explicitly specify the format of your string column; (you can set this in pd.options):
>>> pd.options.display.float_format = '{:,.0f}'.format
>>> df.astype(float).sum()
0 7
1 4
2 11
dtype: float64
Use:
set_indexfor only numeric columnsreplace$with one or more whitespaces\s+- convert to
floats byastype - convert to custom format by
applymap
df = (df.set_index('Names')
.replace('\$\s+','', regex=True)
.astype(float)
.applymap('{:,.2f}'.format))
print (df)
Cider Juice Subtotal (Cider) Subtotal (Juice) Total
Names
Richard 13.00 9.00 71.50 40.50 112.00
George 7.00 21.00 38.50 94.50 133.00
Paul 0.00 23.00 0.00 103.50 103.50
John 22.00 5.00 121.00 22.50 143.50
Total 42.00 58.00 231.00 261.00 492.00
Average 10.50 14.50 57.75 65.25 123.00
EDIT:
I try improve your solution:
people_ordered = input('How many people ordered? ')
Data = []
# Create the 4x3 table from user input
for i in range(int(people_ordered)):
names = input("Enter the name of Person #{}: ".format(i+1)) # type str
cider_orderred = int(input("How many orders of cider did {} have? ".format(names))) # type str -> int
juice_orderred = int(input("How many orders of juice did {} have? ".format(names))) # type str -> int
#create in loop tuple and append to list Data
Data.append((names, cider_orderred, juice_orderred))
#create DataFrame form list of tuples, create index by Names
df1 = pd.DataFrame(Data, columns=['Names','Cider','Juice']).set_index('Names')
#count all new columns, rows
df1['Subtotal(Cider)'] = df1['Cider'] * 5.5
df1['Subtotal(Juice)'] = df1['Juice'] * 4.5
df1['Total'] = df1['Subtotal(Cider)'] + df1['Subtotal(Juice)']
df1.loc['Total'] = df1.sum()
#remove row Total for correct mean
df1.loc['Average'] = df1.drop('Total').mean()
#get custom format of columns in list cols
cols = ['Subtotal(Cider)','Subtotal(Juice)','Total']
df1[cols] = df1[cols].applymap('$ {:,.2f}'.format)
#create column from index
df1 = df1.reset_index()
print(df1)
Names Cider Juice Subtotal(Cider) Subtotal(Juice) Total
0 r 13.0 9.0 $ 71.50 $ 40.50 $ 112.00
1 g 7.0 21.0 $ 38.50 $ 94.50 $ 133.00
2 p 0.0 23.0 $ 0.00 $ 103.50 $ 103.50
3 j 22.0 5.0 $ 121.00 $ 22.50 $ 143.50
4 Total 42.0 58.0 $ 231.00 $ 261.00 $ 492.00
5 Average 10.5 14.5 $ 57.75 $ 65.25 $ 123.00
Just set all floats to 2 digits in general
pd.options.display.float_format = "{:.2f}".format
Although: df['column'].sum() will not become 2 digits...?