The original dataframe contains dots in the number, for instance: 3.200.000. In this case, the dot represents a thousand separator instead of a comma, and I tried to remove the thousand separator using the following code:
pattern_shareholding_numbers = re.compile(r'[\d.]*\d+')
shareholding_percentage_df = df[(~df["Jumlah Lembar Saham"].str.startswith("Saham") & (df["Jabatan"] == "-"))]
shareholding_percentage_df = df[(~df["Jumlah Lembar Saham"].str.startswith("Jumlah Lembar Saham") & (df["Jabatan"] == "-"))]
shareholding_percentage_df.reset_index(drop=True, inplace=True)
shareholding_percentage_list = df["Jumlah Lembar Saham"].to_list()
shareholding_percentage_string = ' '.join(shareholding_percentage_list)
matches = pattern_shareholding_numbers.findall(shareholding_percentage_string)
matches_dot_removed = []
for dot in matches:
dot_removed = []
for e in dot:
e = e.replace('.', '')
e = e.replace('.', '')
dot_removed.append(e)
matches_dot_removed.append(dot_removed)
shareholding_percentage_float = str(matches_dot_removed).rstrip('')
print(shareholding_percentage_float)
The code on the above successfully replaced the thousand separator, and it’s now returning something like the following:
[['3', '', '2', '0', '0', '', '0', '0', '0'], ['2', '', '9', '0', '0', '', '0', '0', '0'], ['2', '', '9', '0', '0', '', '0', '0', '0'], ['1', '', '0', '0', '0', '', '0', '0', '0']]
I am trying to find a way to remove the spacings, and squish the numbers together so that it will be something like:
['3200000'], ['2900000'], ['2900000'], ['1000000']
>Solution :
can convert the data type of the column to string before replacing the dots. You can do this by using the astype() method of the dataframe:
df['column_name'] = df['column_name'].astype(str)
df['column_name'] = df['column_name'].str.replace('.', '')
Once you have converted the data type of the column to string, you can perform the string operation without any issues. After you are done, you can convert the data type back to the original data type if needed.