如何在Python中将2个对象数据类型相乘?

问题描述 投票:0回答:1

这是来自 Udemy 训练营课程(第 76 天)。

我是Python新手。因此,如果我无法正确提出我的问题,请道歉。任何帮助将不胜感激。谢谢。我有一个 Excel 工作表,其中有几列,每列的数据类型如下所示。第 8 行在 Pycharm 中给我一个错误,说我不能乘法。我的 Excel 工作表:apps.csv 有 10 列。请参阅附图。 apps.csv

App                object
Category           object
Rating            float64
Reviews             int64
Size_MBs          float64
Installs           object
Type               object
Price              object
Content_Rating     object
Genres             object
dtype: object

我想将 Excel 工作表中的“价格”和“安装”列相乘,如下所示,并添加一个名为“收入估算”的新列:

import pandas as pd
df=pd.read_csv('apps.csv')
clean_df=df.dropna()
clean_df.loc[:, "Installs"] = clean_df.loc[:, "Installs"].astype(str).str.replace(",", "")
clean_df.loc[:, "Installs"] = pd.to_numeric(clean_df.loc[:, "Installs"])
clean_df.loc[:,"Price"] = clean_df.loc[:,"Price"].astype(str).str.replace('$', "")
clean_df.loc[:, "Price"] = pd.to_numeric(clean_df.loc[:,"Price"])
#Line 8:  
clean_df['Revenue_Estimate']= clean_df.Installs * clean_df.Price

错误:

A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: 
https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
 clean_df['Revenue_Estimate']= clean_df.Installs * clean_df.Price

==============

我也尝试过这个。没用

 df_apps_clean['Revenue_Estimate'] = df_apps_clean.Installs.mul(df_apps_clean.Price)

错误:

A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead
See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
clean_df['Revenue_Estimate'] = clean_df.Installs.mul(clean_df.Price)
python pycharm
1个回答
0
投票
import pandas as pd

df = pd.read_csv('apps.csv')
clean_df = df.dropna()

clean_df['Installs'] = clean_df['Installs'].str.replace(',', '').astype(int)
clean_df['Price'] = clean_df['Price'].str.replace('$', '').astype(float)

clean_df['Revenue_Estimate'] = clean_df['Installs'] * clean_df['Price']

print(clean_df)

尝试将安装量转换为整数,将价格转换为浮动值,这可能对你有用。

© www.soinside.com 2019 - 2024. All rights reserved.