如何从这 68.95 美元中获取 int 值
how to get the int value from this $68.95
我试过了
int(df3.iloc[:,0:1].split('\'')[1])
它说
'DataFrame' object has no attribute 'split'.
我是新手 pandas
你在评论中说你想要 68.95 作为整数。这是不可能的。你可以得到 68 作为整数
int(float(df.iloc[0,0].split('$')[1]))
或者在 float 转换后不转换为 int,作为 68.95 的 float
获取 $price 字符串的数字部分并转换为浮点数(浮点数而不是整数,因为正如其他人所说,1.2 是浮点数而不是整数。我建议替换 '$' 而不是拆分它,以防万一价格有一个没有 $.
的数字
df3 = pd.DataFrame({'price': ['.95', '157.49']})
df3['price_as_number'] = df3['price'].str.replace('$', '').astype(float)
获取 df3:
price price_as_number
0 .95 68.95
1 157.49 157.49
大概您希望对价格列中的每一行都执行此操作,而不仅仅是第一行(零索引)?在 pandas 中有不止一种给猫剥皮的方法,但这可以解决问题。
import pandas as pd
pd.to_numeric(df3['price'].str.lstrip('$')).astype(int)
让我们根据它的评估方式来分解它:
df3['price']
returns 一个系列对象:
0 .95
1 7.49
Name: price, dtype: object
.str.lstrip('$')
对该系列中的每个项目调用字符串处理 lstrip
方法,从而返回一个删除了美元符号的新系列:
0 68.95
1 157.49
Name: price, dtype: object
将该新系列传递给 pd.to_numeric()
,其中 returns 另一个新系列,所有字符串都转换为 float64:
0 68.95
1 157.49
Name: price, dtype: float64
最后 .astype(int)
调用最后一个系列的 astype
方法并将其转换为 int32 dtype。
0 68
1 157
Name: price, dtype: int32
我试过了
int(df3.iloc[:,0:1].split('\'')[1])
它说
'DataFrame' object has no attribute 'split'.
我是新手 pandas
你在评论中说你想要 68.95 作为整数。这是不可能的。你可以得到 68 作为整数
int(float(df.iloc[0,0].split('$')[1]))
或者在 float 转换后不转换为 int,作为 68.95 的 float
获取 $price 字符串的数字部分并转换为浮点数(浮点数而不是整数,因为正如其他人所说,1.2 是浮点数而不是整数。我建议替换 '$' 而不是拆分它,以防万一价格有一个没有 $.
的数字df3 = pd.DataFrame({'price': ['.95', '157.49']})
df3['price_as_number'] = df3['price'].str.replace('$', '').astype(float)
获取 df3:
price price_as_number
0 .95 68.95
1 157.49 157.49
大概您希望对价格列中的每一行都执行此操作,而不仅仅是第一行(零索引)?在 pandas 中有不止一种给猫剥皮的方法,但这可以解决问题。
import pandas as pd
pd.to_numeric(df3['price'].str.lstrip('$')).astype(int)
让我们根据它的评估方式来分解它:
df3['price']
returns 一个系列对象:
0 .95
1 7.49
Name: price, dtype: object
.str.lstrip('$')
对该系列中的每个项目调用字符串处理 lstrip
方法,从而返回一个删除了美元符号的新系列:
0 68.95
1 157.49
Name: price, dtype: object
将该新系列传递给 pd.to_numeric()
,其中 returns 另一个新系列,所有字符串都转换为 float64:
0 68.95
1 157.49
Name: price, dtype: float64
最后 .astype(int)
调用最后一个系列的 astype
方法并将其转换为 int32 dtype。
0 68
1 157
Name: price, dtype: int32