4

I'm just learning python so be gentle. I want to read a file and that to be one function and then have another function work on what the previous function "read". I am having trouble passing the result on one function to another. Here is what I have no far:

I want to call read_file more than once and to be able to pass its result to more than one function, therefore, I do not want frame to be a global variable. How do I get read_file to pass 'frame' to cost_channelID directly? Perhaps, for cost_channelID to call read_file?

def read_file():
    user_input = raw_input("please put date needed in x.xx form: ")
    path = r'C:\\Users\\CP\\documents\\' + user_input
    allFiles = glob.glob(path + '/*.csv')
    frame = pd.DataFrame()
    list = []
    for file in allFiles:
        df = pd.read_csv(file,index_col=None,header=0)
        list.append(df)
    frame =pd.concat(list,ignore_index=True)

def cost_channelID():
    numbers =r'[0,1,2,3,4,5,6,7,8,9]'
    Ads = frame['Ad']
    ID = []
    for ad in Ads:
        num = ''.join(re.findall(numbers,ad)[1:7])
        ID.append(num)
    ID = pd.Series(ID)
    pieces = [frame,ID]


    frame2 = pd.concat(pieces,ignore_index=True,axis=1)
    frame2 = frame2.rename(columns={0:'Ad',1:'Ad Impressions',2:'Total Ad Spend',3:'eCPM (Total Ad Spend/Ad)',4:'Ad Attempts',5:'ID'})

Any and all help is greatly appreciated!

bpr
  • 483
  • 1
  • 11
  • 23
  • If you want the result of `read` to be used by `cost_channelID` then you should make it to receive arguments and/or put `frame` in a global scope. With a better description of the error/problem you get, your question would probably be answered. – Cristián Antuña Apr 16 '15 at 15:07
  • Sounds like I have another problem of not being able to describe my problem! How do I put frame into a global scope so that it can be passed to the cost_channel function? – bpr Apr 16 '15 at 15:10
  • If you `return(frame)` in `read_file` you can call `read_frame = read_file()`. Then `read_frame` is your frame. And, then again, if you define `cost_channelID(received_frame)` and, inside it `Ads = received_frame['Ad']` then you just call `cost_channelID(read_frame)` (And note that `read_frame` is available to be used in any other function) – Cristián Antuña Apr 16 '15 at 15:27
  • I'm not quite sure how to implement that answer without the proper formatting, could you show me how it works within what I've already done? – bpr Apr 16 '15 at 15:34
  • The point is that I'm not sure this is the answer you are looking for, that's why I just comment. If you don't mind me putting it as an answer even tough it may not be an exact one, then I have no problem in putting it in your code. – Cristián Antuña Apr 16 '15 at 15:36
  • I don't mind at all. I am trying to be more exact in what I say. I want read_file() to be used more than once for this program. The point is to reconcile revenue and cost for individual accounts. So eventually I want read_file to read two separate documents and pass those two dataframes to two distinct functions. – bpr Apr 16 '15 at 15:40
  • Head over to [the Python documentation website](http://docs.python.org) and work through the language tutorial, especially the parts about how to `return` values/objects from functions, and assigning those results to variables that can then be passed to other functions... Global variables in Python, as in many other languages, may work, but they are almost always not the best way to do something... – twalberg Apr 16 '15 at 15:48

2 Answers2

1

Here is your modified code (comments in uppercase for easier finding, not rudeness):

def read_file():
    user_input = raw_input("please put date needed in x.xx form: ")
    path = r'C:\\Users\\CP\\documents\\' + user_input
    allFiles = glob.glob(path + '/*.csv')
    frame = pd.DataFrame()
    list = []
    for file in allFiles:
        df = pd.read_csv(file,index_col=None,header=0)
        list.append(df)
    frame =pd.concat(list,ignore_index=True)
    return(frame) #YOUR FUNCTION WILL BE RETURNING THE READ FRAME    

def cost_channelID(read_frame): #YOU WILL BE RECEIVING A DIFFERENT FRAME EVERY TIME
    numbers =r'[0,1,2,3,4,5,6,7,8,9]'
    Ads = read_frame['Ad']
    ID = []
    for ad in Ads:
        num = ''.join(re.findall(numbers,ad)[1:7])
        ID.append(num)
    ID = pd.Series(ID)
    pieces = [frame,ID]


    frame2 = pd.concat(pieces,ignore_index=True,axis=1)
    frame2 = frame2.rename(columns={0:'Ad',1:'Ad Impressions',2:'Total Ad Spend',3:'eCPM (Total Ad Spend/Ad)',4:'Ad Attempts',5:'ID'})
#HERE YOU MEANT TO USE FRAME2 WITHIN THE FUNCTION? IT IS WHAT HAPPENING BECAUSE OF THE INDENTATION

frame1 = read_file() #YOU CAN READ AS MANY FRAMES AS YOU WANT AND THEY'LL BE KEPT IN SEPARATED FRAMES
frame2 = read_file()
#...framexx = read_file() 
#AND YOU CAN JUST CALL cost_channelID in any of them (or any other function)

const_channelID(frame1)
const_channelID(frame2)
#... AND SO ON
  • Thank you! that helps more than you know! And definitely answered my question :) – bpr Apr 16 '15 at 15:53
0

If you are trying to pass frame from one function to the other, you need to declare it outside the scope of the function. Otherwise we need more information about what you are trying to accomplish.

frame = None
def read_file():
    user_input = raw_input("please put date needed in x.xx form: ")
    path = r'C:\\Users\\CP\\documents\\' + user_input
    allFiles = glob.glob(path + '/*.csv')
    frame = pd.DataFrame()
    list = []
    for file in allFiles:
        df = pd.read_csv(file,index_col=None,header=0)
        list.append(df)
    frame =pd.concat(list,ignore_index=True)

def cost_channelID():
    numbers =r'[0,1,2,3,4,5,6,7,8,9]'
    Ads = frame['Ad']
    ID = []
    for ad in Ads:
        num = ''.join(re.findall(numbers,ad)[1:7])
        ID.append(num)
    ID = pd.Series(ID)
    pieces = [frame,ID]


    frame2 = pd.concat(pieces,ignore_index=True,axis=1)
    frame2 = frame2.rename(columns={0:'Ad',1:'Ad Impressions',2:'Total Ad Spend',3:'eCPM (Total Ad Spend/Ad)',4:'Ad Attempts',5:'ID'})

Here is a good reference for scope rules in python Short Description of the Scoping Rules?

Community
  • 1
  • 1
  • I am just trying to pass frame to another function, I'm sure there are a lot of other problems with my code and a lot of possible things i'm trying to accomplish but I'm trying to ask very specific questions about what I am stuck on so I can figure out the rest for myself! – bpr Apr 16 '15 at 15:14
  • Scratch that, I am trying to use read_file more than once! My whole plan is to read two files - the first file will be read and then passed to cost_channelID. The second will be read and then both files will be joined together and processed in another function. How do I get read_file to pass frame to one function at a time? – bpr Apr 16 '15 at 15:18