How to change a column of mixed data to percentage 、 And solve append Replace the previous data problem
df For a with multiple rows and columns dataframe, One of the columns df[' Yield '] There are many types of (float、NAN、 as well as string), I hope that df[' Yield '] Medium float Convert to percentage format , Other data remain the same .
The code is as follows :
def astype_percent(df): t = [] for i in df: use_dict = {} if type(i) == float: if not np.isnan(i): i = '%.2f%%' % (i * 100) if type(i) == str: use_dict = str(i) t.append(use_dict) return pd.Series(t)df[' Yield '] = astype_percent(df[' Yield '])
And found that df[' Yield '] The column as a whole moves forward one line , Cause dislocation 、 The last line is missing .
Checked how to solve it append Replace the previous data , But it didn't work