熊猫:如何更改列的所有值?

bro*_*ues 69 python database pandas

我有一个带有一个列的数据框,"Date"并希望此列中的所有值具有相同的值(仅限年份).例:

City     Date
Paris    01/04/2004
Lisbon   01/09/2004
Madrid   2004
Pekin    31/2004
Run Code Online (Sandbox Code Playgroud)

我想要的是:

City     Date
Paris    2004
Lisbon   2004
Madrid   2004
Pekin    2004
Run Code Online (Sandbox Code Playgroud)

这是我的代码:

fr61_70xls = pd.ExcelFile('AMADEUS FRANCE 1961-1970.xlsx')

#Here we import the individual sheets and clean the sheets    
years=(['1961','1962','1963','1964','1965','1966','1967','1968','1969','1970'])

fr={}

header=(['City','Country','NACE','Cons','Last_year','Op_Rev_EUR_Last_avail_yr','BvD_Indep_Indic','GUO_Name','Legal_status','Date_of_incorporation','Legal_status_date'])

for year in years:
    # save every sheet in variable fr['1961'], fr['1962'] and so on
    fr[year]=fr61_70xls.parse(year,header=0,parse_cols=10)
    fr[year].columns=header
    # drop the entire Legal status date column
    fr[year]=fr[year].drop(['Legal_status_date','Date_of_incorporation'],axis=1)
    # drop every row where GUO Name is empty
    fr[year]=fr[year].dropna(axis=0,how='all',subset=[['GUO_Name']])
    fr[year]=fr[year].set_index(['GUO_Name','Date_of_incorporation'])
Run Code Online (Sandbox Code Playgroud)

碰巧在我的DataFrames中,例如调用fr['1961']的值Date_of_incorporation可以是任何东西(字符串,整数等),所以也许最好完全删除这个列,然后将另一列只有年份附加到DataFrames?

And*_*den 104

正如@DSM指出的那样,您可以使用矢量化字符串方法更直接地执行此操作:

df['Date'].str[-4:].astype(int)
Run Code Online (Sandbox Code Playgroud)

或者使用提取(假设每个字符串中只有一组长度为4的数字):

df['Date'].str.extract('(?P<year>\d{4})').astype(int)
Run Code Online (Sandbox Code Playgroud)

另一种稍微灵活的方法可能是使用apply(或等效map)来执行此操作:

df['Date'] = df['Date'].apply(lambda x: int(str(x)[-4:]))
             #  converts the last 4 characters of the string to an integer
Run Code Online (Sandbox Code Playgroud)

lambda函数正在从中获取输入Date并将其转换为一年.
你可以(也许应该)更详细地写这个:

def convert_to_year(date_in_some_format);
    date_as_string = str(date_in_some_format)
    year_as_string = date_in_some_format[-4:] # last four characters
    return int(year_as_string)

df['Date'] = df['Date'].apply(convert_to_year)
Run Code Online (Sandbox Code Playgroud)

也许'年'是本专栏的更好名称......


小智 17

您可以使用以进行列转换 apply

定义一个干净的函数来删除美元和逗号并将数据转换为浮点数.

def clean(x):
    x = x.replace("$", "").replace(",", "").replace(" ", "")
    return float(x)
Run Code Online (Sandbox Code Playgroud)

接下来,像这样在你的专栏上调用它.

data['Revenue'] = data['Revenue'].apply(clean)
Run Code Online (Sandbox Code Playgroud)


小智 6

或者,如果想在lambda函数中使用apply函数:

data['Revenue']=data['Revenue'].apply(lambda x:float(x.replace("$","").replace(",", "").replace(" ", "")))
Run Code Online (Sandbox Code Playgroud)