如何对熊猫中的字符串执行计算?

时间:2017-07-04 07:42:55

标签: python pandas dataframe

我有一个这样的数据框:

Country     Sales    Assets   
China       4B        320B
China       3B        125B
India       112M      100B
USA         39M       200B...

销售声明列有一些数十亿的值,一些数百万。数十亿用 B 表示,数百万用 M 表示。现在我想检查某个国家/地区的总销售额,但我不能这样做,因为值为对象类型。所以我从列中剥离了 B 并尝试将它们转换为 float 值。但 39M 等值会导致问题。

由于 10亿 = 1000万,我想将数百万的价值转换为数十亿。像 39M 这样的值应该转换为 0.039B 。所以稍后我可以剥离所有 B' 并将它们转换为浮动。

我该怎么做?

2 个答案:

答案 0 :(得分:0)

这样的事情应该有效

data=df['Sales']

for value in data:

     char=value[-1]

     if char=='M'

        toadd=float(value[:-1]/1000.0)

     elif char=='B': 
        toadd=float(value[:-1])

    totalsales=totalsales+toadd

答案 1 :(得分:0)

我认为你可以在while True: ret,img=cap.read() if ret == True: cv2.imshow('video output', img) k=cv2.waitKey(10)& 0xff if k==27: break cap.release() cv2.destroyAllWindows() s:

中使用if need输出
float

如果您想要更改数字值,只需更改cols = ['Sales','Assets'] d = {'M': 10**-3, 'B':1} df[cols] = df[cols].apply(lambda x: x.str[:-1] .astype(int).mul(x.replace(d, regex=True)) .astype(float)) print (df) Country Sales Assets 0 China 4.000 320.0 1 China 3.000 125.0 2 India 0.112 100.0 3 USA 0.039 200.0 值:

dict