【发布时间】:2022-11-02 14:50:59
【问题描述】:
我有一个数据集,其中价格列作为字符串类型,一些值采用范围(15000-20000)的形式。 我想提取第一个数字并将整列转换为整数。
我试过这个:
df['ptice'].apply(lambda x:x.split('-')[0])
代码只返回原始列。
【问题讨论】:
我有一个数据集,其中价格列作为字符串类型,一些值采用范围(15000-20000)的形式。 我想提取第一个数字并将整列转换为整数。
我试过这个:
df['ptice'].apply(lambda x:x.split('-')[0])
代码只返回原始列。
【问题讨论】:
尝试以下选项之一:
数据
import pandas as pd
data = {'price': ['0','100-200','200-300']}
df = pd.DataFrame(data)
print(df)
price
0 0 # adding a str without `-`, to show that this one will be included too
1 100-200
2 200-300
选项1
Series.str.split 和expand=True 并从结果中选择第一列。Series.astype,并将结果分配给df['price'] 以覆盖原始值。
df['price'] = df.price.str.split('-', expand=True)[0].astype(int)
print(df)
price
0 0
1 100
2 200
选项 2
Series.str.extract 与正则表达式模式一起使用r'(d+)-?':d 匹配一个数字。+ 匹配数字 1 次或多次。- 时匹配停止(? 指定“如果存在”)。
data = {'price': ['0','100-200','200-300']}
df = pd.DataFrame(data)
df['price'] = df.price.str.extract(r'(d+)-?').astype(int)
# same result
【讨论】:
这是执行此操作的一种方法:
df['price'] = df['price'].str.split('-', expand=True)[0].astype('int')
这将只存储范围中的第一个数字。示例:从 15000 到 20000,只有 15000 将存储在 price 列中。
【讨论】: