Search code examples
pythonpandasargs

Using *arg in to assign value to pandas column


I'd like to define a DataFrame using *arg. I want to use the special syntax *args pass a variable number of arguments to a data frame column as follow:

import pandas as pd

def test(*args):
    data = pd.DataFrame()
    for arg in args:
        data[str(arg)] = arg
    print(data)

test(1, 'a', 'b', 2)

I expect that the output is a data Frame with the columns [1, a, b, 2] and the respective values. But I only get an empty DataFrame.


Solution

  • Try this code:

    import pandas as pd
    
    def test(*args):
        data = pd.DataFrame()
        for arg in args:
            data[str(arg)] = [arg]
        print(data)
    
    test(1, 'a', 'b', 2)