我正在尝试将价格列与整数相乘,但是这没有发生。
for index,row in df.iterrows():
a=row['price']
row['price'] = a[1:]
b = row['price'].split(' ')[1]
因此,我想乘以100000(其中价格带有“ L”)和10000000(其中价格带有“ Cr”)。
例如,第一个单元格为50.0 L,因此输出应为5000000.0
我使用了dtype
,输出为dtype('O')
price area type price per sq feet Address
0 50.0 L 650 1 7.69 Mankhurd
1 1.15 Cr 650 1 17.69 Chembur
2 95.0 L 642 1 14.80 Bhandup West
3 1.6 Cr 650 2 24.61 Goregaon East
5 88.0 L 570 1 15.44 Borivali East
我将非常感谢您的帮助。 谢谢Yoo
答案 0 :(得分:2)
IIUC,您可以将series.str.extract
与series.map
进行乘法运算:
d = {"L":100000,"Cr":10000000}
pat = '|'.join(d.keys())
mapped = df['price'].str.extract('('+pat+')',expand=False).map(d)
df['price'] = pd.to_numeric(df['price'].str.replace(pat,''),errors='coerce') * mapped
print(df)
price area type price per sq feet Address
0 5000000.0 650 1 7.69 Mankhurd
1 11500000.0 650 1 17.69 Chembur
2 9500000.0 642 1 14.80 Bhandup West
3 16000000.0 650 2 24.61 Goregaon East
4 8800000.0 570 1 15.44 Borivali East
答案 1 :(得分:1)
def func(element):
num, type = element.split()
if type == 'L' : return float(num) * 10**5
if type == 'Cr': return float(num) * 10**7
df['price'] = df['price'].apply(func)
答案 2 :(得分:0)
一种实现方法是编写一个函数来处理您要如何对待每个元素,然后在相关列上使用map函数:
def convert_price(price):
price_value = float(price.split(" ")[0])
if "L" in price:
return price_value*100000
elif "Cr" in price:
return price_value*10000000
else:
return price # or however else you want to handle it
df["price_converted"] = df["price"].map(convert_price)