英文:
Trasnforming, kg ml, l, proportion into g proportion
问题
Here's the translated code portion:
我有以下的pd.Series
s = pd.Series(['3.95/kg', '3.30/kg', '3.49/kg', '3.96/g', '8.49/kg', '3.19/kg',
'0.0154/g', '8.98/kg', '6.35/kg', '5.79/kg', '3.79/kg', '6.59/kg',
'3.50/kg', '3.85/kg', '3.55/kg', '5.59/kg', '5.98/kg', '0.0152/g',
'5.99/kg', '3.20/gr', '8.99/kg', '16.90/kg', '4.29/kg',
'0.0128/g', '5.29/kg', '3.39/kg', '6.29/kg', '4.59/kg',
'28.90/kg', '4.69/kg', '0.0389/gr', '0.0099/ml', '0.0608/g',])
我想要做的是将每个比例转化为一个单一的值,例如,如果它是以千克为单位的。将比例转化为克,同样适用于毫升和升的比例。
所以,例如,我们有字符串中的'3.95/kg'。我想要相同的比例,但以克为单位,这意味着我们需要除以1000,所以它变成了'0.00395/g'。如果字符串包含毫升,那么它保持不变。如果它包含升,那么它除以1000。
期望的结果
pd.Series(['0.00395/g','0.00330/g','0.00349/g','3.96/g']) # 以此类推
有关如何使用pandas执行此处理的想法吗?
英文:
I have the following pd.Series
s = pd.Series(['3.95/kg', '3.30/kg', '3.49/kg', '3.96/g', '8.49/kg', '3.19/kg',
'0.0154/g', '8.98/kg', '6.35/kg', '5.79/kg', '3.79/kg', '6.59/kg',
'3.50/kg', '3.85/kg', '3.55/kg', '5.59/kg', '5.98/kg', '0.0152/g',
'5.99/kg', '3.20/gr', '8.99/kg', '16.90/kg', '4.29/kg',
'0.0128/g', '5.29/kg', '3.39/kg', '6.29/kg', '4.59/kg',
'28.90/kg', '4.69/kg', '0.0389/gr', '0.0099/ml', '0.0608/g',])
What I want to do is to transform every single proportions into one single value for example, with it is in kg. Transform the proportion into grams, the same goess with ml and l proporitons.
So for example we got 3.95/kg on the string. I want the same proportion but in grams meaning we got to divide it by 1000 so it goes to 0.00395/g. If the string contains an ml well it remains the same. If it contains an l well it divides by 1000
Wanted result
pd.Series(['0.00395/g','0.00330/g','0,00349/g','3.96/g']) # And so on
Any ideas on how to do this treamtment utilizing pandas?
答案1
得分: 1
以下是您要翻译的内容:
s = pd.Series(['3.95/kg', '3.30/kg', '3.49/kg', '3.96/g', '1.2/l', '0.0099/ml'])
df = s.str.split('/', expand=True)
(df[0]
.astype('float')
.div(df[1].map({'kg':1000, 'g':1, 'l':1000, 'ml':1}))
.astype('str')
.str.cat(df[1].replace({'kg': 'g', 'l':'ml'}), sep='/'))
输出:
0 0.00395/g
1 0.0033/g
2 0.00349/g
3 3.96/g
4 0.0012/ml
5 0.0099/ml
dtype: object
英文:
Example
s = pd.Series(['3.95/kg', '3.30/kg', '3.49/kg', '3.96/g', '1.2/l', '0.0099/ml'])
s
0 3.95/kg
1 3.30/kg
2 3.49/kg
3 3.96/g
4 1.2/l
5 0.0099/ml
dtype: object
Code
df = s.str.split('/', expand=True)
df
0 1
0 3.95 kg
1 3.30 kg
2 3.49 kg
3 3.96 g
4 1.2 l
5 0.0099 ml
make desired ouput by df[0]
and df[1]
(df[0]
.astype('float')
.div(df[1].map({'kg':1000, 'g':1, 'l':1000, 'ml':1}))
.astype('str')
.str.cat(df[1].replace({'kg': 'g', 'l':'ml'}), sep='/'))
output:
0 0.00395/g
1 0.0033/g
2 0.00349/g
3 3.96/g
4 0.0012/ml
5 0.0099/ml
dtype: object
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论