簡體   English   中英

如何根據條件更改pd.DataFrame的值?

[英]How to change value of a pd.DataFrame based on a condition?

我有FIFA數據集,其中包含有關足球運動員的信息。 該數據集的特征之一是足球運動員的價值,但它是字符串形式,例如“ $ 300K”或“ $ 50M”。 如何簡單地刪除這些歐元和“ M,K”符號,並以相同單位寫入它們的值?

import numpy as np
import pandas as pd

location = r'C:\Users\bemrem\Desktop\Python\fifa\fifa_dataset.csv'

_dataframe = pd.read_csv(location)

_dataframe = _dataframe.dropna()
_dataframe = _dataframe.reset_index(drop=True)
_dataframe = _dataframe[['Name', 'Value', 'Nationality', 'Age', 'Wage', 
'Overall', 'Potential']]

_array = ['Belgium', 'France', 'Brazil', 'Croatia', 'England',' Portugal', 
'Uruguay', 'Switzerland', 'Spain', 'Denmark']

_dataframe = _dataframe.loc[_dataframe['Nationality'].isin(_array)]
_dataframe = _dataframe.reset_index(drop=True) 


print(_dataframe.head())
print()
print(_dataframe.tail())

我試圖轉換此“值”列,但失敗了。 這就是我得到的

           Name   Value Nationality  Age   Wage  Overall  Potential
0        Neymar   €123M      Brazil   25  €280K       92         94
1     L. Suárez    €97M     Uruguay   30  €510K       92         92
2     E. Hazard  €90.5M     Belgium   26  €295K       90         91
3  Sergio Ramos    €52M       Spain   31  €310K       90         90
4  K. De Bruyne    €83M     Belgium   26  €285K       89         92

              Name Value Nationality  Age Wage  Overall  Potential
4931    A. Kilgour  €40K     England   19  €1K       47         56
4932      R. White  €60K     England   18  €2K       47         65
4933     T. Sawyer  €50K     England   18  €1K       46         58
4934     J. Keeble  €40K     England   18  €1K       46         56
4935  J. Lundstram  €60K     England   18  €1K       46         64

但是我想我的輸出看起來像這樣:

           Name   Value Nationality  Age   Wage  Overall  Potential
0        Neymar   123      Brazil   25  €280K       92         94
1     L. Suárez    97     Uruguay   30  €510K       92         92
2     E. Hazard  90.5     Belgium   26  €295K       90         91
3  Sergio Ramos    52       Spain   31  €310K       90         90
4  K. De Bruyne    83     Belgium   26  €285K       89         92

              Name Value Nationality  Age Wage  Overall  Potential
4931    A. Kilgour  0.04     England   19  €1K       47         56
4932      R. White  0.06     England   18  €2K       47         65
4933     T. Sawyer  0.05     England   18  €1K       46         58
4934     J. Keeble  0.04     England   18  €1K       46         56
4935  J. Lundstram  0.06     England   18  €1K       46         64

我的信譽不足,無法將答案標記為重復。 但是,我相信,如果字符串中沒有“ K”或“ M”,那么除了提供解決方案之外,它還能解決您的特定問題。

您還需要在正則表達式中用替換$

在熊貓數據框中將字符串2.90K轉換為2900或將5.2M轉換為5200000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM