问题
I have the following data frame:
Date Ratio
0 2000-06-21 4:1
1 2000-06-22 3:2
2 2000-06-23 5:7
3 2000-06-24 7:1
For each item in the Ratio
column, I want to reverse the ratio, convert it into a fraction and convert it to a float.
Meaning 4:1 would become 1:4, then the : would be replaced with a / and finally it would get 0.25. 3:2 would become 2/3 which is converted to 0.66666666666.
So far I only have the following code:
df['Ratio'] = df['Ratio'].str.split(":")
回答1:
Create new DataFrame
with expand=True
in Series.str.split, convert to integers and last divide columns:
df1 = df['Ratio'].str.split(":", expand=True).astype(int)
df['Ratio'] = df1[1].div(df1[0])
For one line solution is possible use DataFrame.set_axis and DataFrame.eval:
df['Ratio'] = (df['Ratio'].str.split(":",expand=True)
.astype(int)
.set_axis(['a','b'], inplace=False, axis=1)
.eval('b/a'))
print (df)
Date Ratio
0 2000-06-21 0.250000
1 2000-06-22 0.666667
2 2000-06-23 1.400000
3 2000-06-24 0.142857
回答2:
How about:
df['Ratio'] = df['Ratio'].apply(lambda x: 1 / eval(x.replace(':', '/')))
Or:
df['Ratio'] = 1 / df['Ratio'].str.replace(':', '/').apply(eval)
Or as commented by @anky_91, pd.eval
also works:
df['Ratio'] = 1 / pd.eval(df['Ratio'].str.replace(':', '/'))
回答3:
You can also use your own function, for example this one:
def get_new_ratio(ratio):
ratio_splitted = list(map(int, ratio.split(':')))
return ratio_splitted[1] / ratio_splitted[0]
And after that use it as an argument in pandas.DataFrame.apply():
>>> df['new_ratio'] = df.Ratio.apply(get_new_ratio)
>>> print(df)
Date Ratio new_ratio
0 2000-06-21 4:1 0.250000
1 2000-06-22 3:2 0.666667
2 2000-06-23 5:7 1.400000
3 2000-06-24 7:1 0.142857
来源:https://stackoverflow.com/questions/60739797/how-to-flip-a-column-of-ratios-convert-into-a-fraction-and-convert-to-a-float