mintux :
I have a dataframe containing a column with numbers like this:
1. 34.5
2. 345.2
3. 898.4-
4. 87.4
...
n. 847.3-
The column is str, now I have written a code that cycles the whole column (about 19 million rows). I ask if anyone knows a faster method to bring the "-" in front and change the str to number
My code:
for i, row in frame.iterrows():
Val=row[9]
if row[9].find("-") > 0 :
Val="-"+row[9].replace("-","")
frame.iloc[i,9]=Val
frame[frame.columns[9]]=pd.to_numeric(frame[frame.columns[9]]
Serge Ballesta :
You can do it directly with the help of str
:
frame.loc[frame[col_name].str[-1] == '-', col_name] = '-' + frame.loc[
frame[col_name].str[-1] == '-', col_name].str.replace('-', '')
frame[col_name] = frame[col_name].astype('float')
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=320075&siteId=1