the question I have pertains to formatting in pandas / python. The question below is stated.
The trading volume numbers are large. Scale the trading volume to be in millions of shares. Ex: 117,147,500 shares will become 117.1475 million after scaling.
This is what the dataframe looks like. I need it to be fixed for all 125 rows.
CodePudding user response:
Probably the simplest way is to divide the whole column by a million
apple['volume'] = apple['volume'].div(1000000)
CodePudding user response:
You can use transform() method (https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.transform.html) and divide those volume numbers by 1000,000.
CodePudding user response:
You can substitute numbers like 117147500 in the following two ways: either with floating point numbers:
import pandas as pd
dictionary = {'Column':[4,5,6,7], 'Volume':[117147500,12000,14000,18000]}
df = pd.DataFrame(dictionary)
df
df_scaled_column=df['Volume']/1000000
# Replace old column with scaled values
df['Volume'] = df_scaled_column
df
Out:
Column Volume
0 4 117.1475
1 5 0.0120
2 6 0.0140
3 7 0.0180
or with strings. In particular I use a function that I found from an answer to this SE post formatting long numbers as strings in python:
import pandas as pd
dictionary = {'Column':[4,5,6,7], 'Volume':[117147500,12000,14000,18000]}
df = pd.DataFrame(dictionary)
df
# Function defined in a old StackExchange post
def human_format(num):
num = float('{:.3g}'.format(num))
magnitude = 0
while abs(num) >= 1000:
magnitude = 1
num /= 1000.0
return '{}{}'.format('{:f}'.format(num).rstrip('0').rstrip('.'), ['', 'K', 'M', 'B', 'T'][magnitude])
# Example of what the function does
human_format(117147500) #'117M'
# Create empty list
numbers_as_strings = []
# Fill the empty list with the formatted values
for number in df['Volume']:
numbers_as_strings.append(human_format(number))
# Create a dataframe with only one column containing formatted values
dictionary = {'Volume': numbers_as_strings}
df_numbers_as_strings = pd.DataFrame(dictionary)
# Replace old column with formatted values
df['Volume'] = df_numbers_as_strings
df
Out:
Column Volume
0 4 117M
1 5 12K
2 6 14K
3 7 18K