Using *arg in to assign value to pandas column

Question:

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.

Asked By: Metariat

||

Answers:

Use this,

import pandas as pd

def test(*args):
    di = dict((str(x), x) for x in args)
    data = pd.DataFrame.from_dict([di])
    print(data)

SAMPLE OUTPUT

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

   1  2  a  b
0  1  2  a  b

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)

Answered By: daidai21
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.