【问题标题】:object of type 'float' has no len() on a string object'float' 类型的对象在字符串对象上没有 len()
【发布时间】:2019-10-27 04:38:40
【问题描述】:

我正在尝试转换我的数据框中的一列,该列的名称是“重量”,它具有 str 格式的值

例如:"175lbs"

我正在使用映射器将所有这些值转换为float

我使用映射器尝试了 lambda 函数

def WeightConverter(w):
    return float(w[:len(w)-3])

df1['Weight'] = df1.Weight.map(lambda x : WeightConverter(x))
df1['Weight'].head()

但是,type(df1['Weight'][0]) 返回str。预期结果:175.0 类型为 float

【问题讨论】:

  • df1 是我的数据框
  • WeightConverter 中你可以只使用return float(w[:-3]),否则这对我有用。
  • 用apply代替map试试
  • 任何使用 apply ansev 的例子
  • 'float' 对象在执行 return float(w[:-3]) 时不可下标

标签: python-3.x pandas


【解决方案1】:

先尝试使用正则表达式提取您的数字,然后您可以进行任何进一步的操作。

df = pd.DataFrame({'Weight' : np.random.randint(0,250,size=500)})
df['Weight'] = df['Weight'].astype(str) + 'lbs'
print(df.head(10))
   Weight
0  224lbs
1   11lbs
2  218lbs
3  132lbs
4   55lbs
5   87lbs
6   62lbs
7    4lbs
8   38lbs
9  218lbs

然后使用(\d+)str.extract

df['Weight_Float'] = df['Weight'].str.extract(r'(\d+(?:\.\d+)?)').astype(float)
    print(df.head(10))
     Weight  Weight_Float
0  119lbs         119.0
1    7lbs           7.0
2  241lbs         241.0
3   85lbs          85.0
4  144lbs         144.0
5  219lbs         219.0
6  160lbs         160.0
7  173lbs         173.0
8  166lbs         166.0
9   35lbs          35.0

说明:

  • (启动捕获组
  • \d 一个速记字符类,匹配所有数字;它是 与 [0-9] 相同
  • + 一个或多个表达式
  • )结束一个捕获组

【讨论】:

  • 如果字符串为 119.20lbs 并且所需的输出为 119.20,这将起作用
  • @GaneshRam 我已经编辑了正则表达式来为你提取浮点数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-15
  • 2021-01-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多