如何创建一个函数来将数据附加到数据框?

时间:2017-09-30 20:23:22

标签: python pandas dataframe

import pandas as pd
columns_list=['sport','home','away','selection','odds','tipster','stake',
              'is_won','profit','bookie']

df = pd.DataFrame(columns=columns_list)

def bet(sport,home,away,selection,odds,tipster,stake,profit,bookie):
    if profit > 0:
        is_won = True
    elif profit < 0:
        is_won = False
    temp_df = pd.DataFrame([[sport,home,away,selection,odds,tipster,stake,
                             is_won,profit,bookie]], columns=columns_list)
    df.append(temp_df, ignore_index=True)
    #print(smemels has been inserted)
    #add market

bet(sport="football",home="sporting",away="porto",selection="sporting",
    odds=2.7,tipster="me",stake=500,profit=500,bookie="marathon")

我正在尝试创建一个空DataFrame,然后通过创建一个函数来追加新行,所以我只需要放置值并自动插入。当我运行代码bet(...)时,它并没有真正附加数据。

2 个答案:

答案 0 :(得分:0)

def bet(**kwargs):
    '''place your code here

bet(sport="football",home="sporting",away="porto",selection="sporting",
odds=2.7,tipster="me",stake=500,profit=500,bookie="marathon")

请参阅http://book.pythontips.com/en/latest/args_and_kwargs.html

kwargs允许您添加keyworded,就像您尝试做的那样。

答案 1 :(得分:-1)

只需添加&#34;全球df&#34;在你的函数头下面和参数inplace = True in append function:

def bet(sport,home,away,selection,odds,tipster,stake,profit,bookie):
    global df
    if profit > 0:
        is_won = True
    elif profit < 0:
        is_won = False
    temp_df = pd.DataFrame([[sport,home,away,selection,odds,tipster,stake,
                             is_won,profit,bookie]], columns=columns_list)
    df.append(temp_df, ignore_index=True, inplace = True)

第一个告诉函数采用全局(函数外)df变量而不是在本地创建一个新变量。第二个更改数据帧而不是返回新对象。