作者热门文章
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在尝试将我的数据集的字符串转换为浮点类型。这里有一些背景:
import pandas as pd
import numpy as np
import xlrd
file_location = "/Users/sekr2/Desktop/Jari/Leistungen/leistungen2_2017.xlsx"
workbook = xlrd.open_workbook(file_location)
sheet = workbook.sheet_by_index(0)
df = pd.read_excel("/Users/.../bla.xlsx")
df.head()
Leistungserbringer Anzahl Leistung AL TL TaxW Taxpunkte
0 McGregor Sarah 12 'Konsilium' 147.28 87.47 KVG 234.75
1 McGregor Sarah 12 'Grundberatung' 47.00 67.47 KVG 114.47
2 McGregor Sarah 12 'Extra 5min' 87.28 87.47 KVG 174.75
3 McGregor Sarah 12 'Respirator' 147.28 102.01 KVG 249.29
4 McGregor Sarah 12 'Besuch' 167.28 87.45 KVG 254.73
为了继续努力,我需要找到一种创建新专栏的方法:df['Leistungswert'] = df['Taxpunkte'] * df['Anzahl'] * df['TaxW']
。
TaxW 为每个条目显示字符串“KVG”。我从数据中得知“KVG”= 0.89。我在尝试将字符串转换为 float 时遇到了困难。我不能只创建一个 float 类型的新列,因为此代码应该适用于更多输入。在 TaxW 列中,大约有 7 个具有所有不同值的不同条目。
我感谢有关此事的所有信息。
最佳答案
假设 'KVG'
不是 TaxW
中唯一可能的字符串值,您应该将字符串映射存储到它们的等效 float ,如下所示:
map_ = {'KVG' : 0.89, ... } # add more fields here
然后,您可以使用Series.map
:
In [424]: df['Leistungswert'] = df['Taxpunkte'] * df['Anzahl'] * df['TaxW'].map(map_); df['Leistungswert']
Out[424]:
0 2507.1300
1 1222.5396
2 1866.3300
3 2662.4172
4 2720.5164
Name: Leistungswert, dtype: float64
或者,您可以使用df.transform
:
In [435]: df['Leistungswert'] = df.transform(lambda x: x['Taxpunkte'] * x['Anzahl'] * map_[x['TaxW']], axis=1); df['Lei
...: stungswert']
Out[435]:
0 2507.1300
1 1222.5396
2 1866.3300
3 2662.4172
4 2720.5164
Name: Leistungswert, dtype: float64
关于python - 如何将 str 转换为 pandas 中的 float,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45143402/
我是一名优秀的程序员,十分优秀!