-1

I have a function that creates and prints a Dataframe based on the contents of a file:

import pandas as pd

def DataFrameConverter(file):

    T = pd.read_fwf(file, header= None, names=['1','2','3','4','5','6','7','8','9'])
    T = T.rename(index={0:'A',1:'B',2:'C',3:'D',4:'E',5:'F',6:'G',7:'H',8:'I'})

    df = pd.DataFrame(T)
    print(df)

and a function that is supposed to allow the user to modify a DataFrame, by replacing 'X' values with user input:

def modifyDF(variable):

    while df.isin(['X']).any().any():
        
        print('')
        x = input('row: ')
        y = input('col: ')
        v = input('value: ')
        print('')
        
        df.loc[x,y] = v
        print(df)

Now I want to ask the user for a file name, read the DataFrame, and ask the user to modify it. I tried calling the conversion function and saving the result like so:

variable = DataFrameConverter(file = input('File name: '))

and then passing it like so:

modifyDF(variable)

However, I get errors saying that df is not defined. What is wrong with the code? How can I make modifyDF use the DataFrame that was created by DataFrameConverter?

prg_flks
  • 35
  • 4
  • 1
    Can you edit your question to be more concise? What *exactly* are you looking to achieve? Are you looking for an example how how you can pass functions are arguments? In addition, your code currently doesn't compile. Please upload code that compiles **or** highlight exactly what the issue is with the code you're looking to fix (along with some sample data) – dalekman1234 Jan 02 '23 at 20:40
  • 1
    Welcome to Stack Overflow. "I have saved the DataFrameConverter function in a variable" No; you have saved the **result of calling** that function. That said, it still isn't clear how you want this to work. What do you mean by "every time I create a new function" - what new functions, for what purpose, and how do they relate to this code? What do you mean by "convert the text file" - which files, and how do they relate to this code? Bluntly, I think you are struggling to explain the problem because you are not thinking clearly about **what the words mean**. – Karl Knechtel Jan 02 '23 at 20:47
  • 1
    So, start over. Walk through the steps. What happens first - the user inputs a file name? And then you want to open that file, convert it to a dataframe, and process it with `modify_df`? And then what - do you enter more file names, in a loop? Or just what? What have other functions got to do with any of this? – Karl Knechtel Jan 02 '23 at 20:51
  • 1
    When you call the `modifyDF` function, **what do you want it to do with** the `variable` that was passed in? (I don't see any code right now, in `modifyDF`, that would try to **use** `variable`. Is the problem simply about how to pass information between functions? – Karl Knechtel Jan 02 '23 at 20:52
  • Thanks for the feedback guys! I appreciate these comments for proper use of StackOverflow. It is true that I did not know how to explain myself well. I'll try to edit the post to make it more understandable :) – prg_flks Jan 02 '23 at 20:57
  • 2
    Does [How do I get a result (output) from a function? How can I use the result later?](/questions/3052793) answer your question? Or how about [What is the purpose of the return statement? How is it different than printing?](https://stackoverflow.com/questions/7129285/)? – Karl Knechtel Jan 02 '23 at 21:16
  • I will check these links. Thank you for sharing them @Karl Knechtel. By the way, I have modified the question. Is it clearer now? – prg_flks Jan 02 '23 at 21:30
  • 1
    Okay, so the goal is that you want the `modifyDF` function **to use** some DataFrame **that you got as a result** from calling `DataFrameConverter`? – Karl Knechtel Jan 02 '23 at 21:32
  • Exactly @Karl Knechtel. – prg_flks Jan 02 '23 at 21:33
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/250794/discussion-between-karl-knechtel-and-prg-flks). – Karl Knechtel Jan 02 '23 at 21:43
  • Don't try to do too much in a single line of code. Instead of `variable = DataFrameConverter(file = input('File name: '))` (which isn't valid syntax anyway), split it into two lines: `file = input('File name: ')` and `variable = DataFrameConverter(file)`. Also don't use the variable name `variable`. Use something more descriptive. In this case `df` is common. – Code-Apprentice Jan 03 '23 at 02:44

2 Answers2

1

Without knowing the exact specifics of what you're looking to achieve, I think what you're getting at is wanting to return the dataframe from your first function to be used later.

import pandas as pd

def DataFrameConverter(file):
    T = pd.read_fwf(file, header=None, names=[
                    '1', '2', '3', '4', '5', '6', '7', '8', '9'])
    T = T.rename(index={0: 'A', 1: 'B', 2: 'C', 3: 'D',
                 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I'})
    df = pd.DataFrame(T)
    print(df)
    return df

data_frame = DataFrameConverter(file=input('File name: '))

def modifyDF(data_frame):
    df = data_frame
    while df.isin(['X']).any().any():
        print('')
        x = input('row: ')
        y = input('col: ')
        v = input('value: ')
        print('')
        df.loc[x, y] = v
        print(df)

modifyDF(data_frame)

Or perhaps you want to use a global variable that each function accesses:

import pandas as pd

df: pd.DataFrame = None
def DataFrameConverter(file):
    T = pd.read_fwf(file, header=None, names=[
                    '1', '2', '3', '4', '5', '6', '7', '8', '9'])
    T = T.rename(index={0: 'A', 1: 'B', 2: 'C', 3: 'D',
                 4: 'E', 5: 'F', 6: 'G', 7: 'H', 8: 'I'})
    df = pd.DataFrame(T)
    print(df)

DataFrameConverter(file=input('File name: '))

def modifyDF():
    while df.isin(['X']).any().any():
        print('')
        x = input('row: ')
        y = input('col: ')
        v = input('value: ')
        print('')
        df.loc[x, y] = v
        print(df)

modifyDF()

dalekman1234
  • 229
  • 2
  • 8
  • 1
    So all I had to do is redefine `df` as `data_frame`. So it can collect the output of the `DataFrameConverter` function. Perfect @dalekman1234. Very clear response. Thank you and have a good day! – prg_flks Jan 02 '23 at 22:15
1

Minimum to get what you want

In your DataFrameConverter function, you aren't actually returning any results.

I think if you change your line:

print(df)

To be:

return (df)

You'll get what you're wanting.

Side Notes

  • Having a variable named 'variable' is literal eye cancer. Since it's a pandas dataframe I would just store it as 'df' or 'dataframe'.

  • DataFrameConverter is really just reading a pandas dataframe from a text file. So your code would be easier to follow if you had function names such as 'read_data' and 'modify_data'.

Kaleb Fenley
  • 216
  • 1
  • 5