[英]How to convert the column in US million dollars in pandas?
我有一個名為collection的列如下
收集:$ 5,345,677,46836214,$ 533,316,061,“”,29200000
列值既有美元也有美元。 此外,它有NAN。 我想換成百萬美元
我以前轉換如下,但沒有成功
df['Boxoffice in US$ (mil)'] = (df2['collection'].astype(float)/1000000).round(2).astype(str)
得到此錯誤:無法將字符串轉換為浮點數:'$ 5,345,677'
請指教
# remove the '$' and ',' from the strings so it can be converted to numerics
# -> notice: the series is converted to strings to handle numerics (eg. 29200000)
collection_tmp = df2['collection'].astype(str).str.replace('[$,]', '')
# convert to numerics (floats) and then to millions
# -> errors='coerce' sets NaN for invalid values
millions = pd.to_numeric(collection_tmp, errors='coerce')/1e6
# create 'Boxoffice in US$ (mil)'
df['Boxoffice in US$ (mil)'] = millions.round(2).astype('str')
您可以參考以下步驟:
1.填寫NAN或空白值(空白區域)。 你說它有南,但我看到了“”。
[in ]: df['collection']
[out]: collection
0 $5,345,677
1 46836214
2 $533,316,061
3
4 29200000
[in ]: # if you have Nan, just use method `fillna` instead
# like df['collection'].fillna('0')
[in ]: df['collection'].replace(r'^\s*$', '0', regex=True)
[out]: collection
0 $5,345,677
1 46836214
2 $533,316,061
3 0
4 29200000
然后將數字轉換為“百萬美元”。
[in ]: df['collection'].apply(lambda x: ''.join(('$', format(int(x), ','))) if not '$' in x else x)
[out]: collection
0 $5,345,677
1 $46,836,214
2 $533,316,061
3 $0
4 $29,200,000
我希望這可以幫到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.