gpt4 book ai didi

python - Pandas :根据另一列的内容乘以一列

转载 作者:太空宇宙 更新时间:2023-11-04 00:13:30 25 4
gpt4 key购买 nike

我试图从该列中获取 Market Cap 作为 float

Company Info
Workhorse Group, Inc. (WKHS) Market Cap: $65.94M
Xencor, Inc. (XNCR) Market Cap: $1.99B
Zillow Group, Inc. (ZG) Market Cap: $10.28B
Zillow Group, Inc. (Z) Market Cap: $10.17B
Zogenix, Inc. (ZGNX) Market Cap: $1.99B

期望的输出

Market Cap
65940000.00
1990000000.00
10280000000.00
10170000000.00
1990000000.00

我可以用这个得到号码(可能是更好的方法)

df['market_cap'] = df['Company Info'].str.split('$').str.get(1).str[:-1]

market_cap
1.13B
283.56M
763.51M
231.31M
1.3B

但我需要它作为 float ,乘数基于 Company Info 列末尾的 MB

multiplier = {'M': 1e6, 'B': 1e9}

最佳答案

循序渐进

基本上按照您的方式提取 market_cap,除了转换为 float :

df['market_cap'] = df['Company Info'].str.split('$').str.get(1).str[:-1].astype(float)

使用正则表达式提取乘数:

df['multiplier'] = df['Company Info'].str.extract('\d+\.\d+(\w)')

将您的市值乘以您提供的映射:

df['Market Cap'] = df.market_cap.mul(df['multiplier'].map({'M': 1e6, 'B': 1e9}))

>>> df['Market Cap']
0 6.594000e+07
1 1.990000e+09
2 1.028000e+10
3 1.017000e+10
4 1.990000e+09
Name: Market Cap, dtype: float64

在一个声明中

这里和单行一样:

df['Market Cap'] = (df['Company Info'].str.split('$')
.str.get(1).str[:-1]
.astype(float)
.mul(df['Company Info']
.str.extract('\d+\.\d+(\w)')
.map({'M': 1e6, 'B': 1e9})))

>>> df
Company Info Market Cap
0 Workhorse Group, Inc. (WKHS) Market Cap: $65.94M 6.594000e+07
1 Xencor, Inc. (XNCR) Market Cap: $1.99B 1.990000e+09
2 Zillow Group, Inc. (ZG) Market Cap: $10.28B 1.028000e+10
3 Zillow Group, Inc. (Z) Market Cap: $10.17B 1.017000e+10
4 Zogenix, Inc. (ZGNX) Market Cap: $1.99B 1.990000e+09

关于python - Pandas :根据另一列的内容乘以一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51717920/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com