简体   繁体   中英

Get every pandas dataframe column names separately inside a list

I have a pandas dataframe and want to extract each column name individually and append it inside a list.

I tried something like this:

def get_hist_data(data):
    # create an empty list
    histdata = []
    for col in data.columns:
        test_list = "data['{}']".format(col)
        histdata += [test_list]
    histdata = '[%s]' % ', '.join(map(str, histdata))

    return histdata

and output I got is a list where data is a string now:

[data['A'], data['B'],data['C']]

I don't want data as a string but want this as the dataframe which I passed as a parameter of my function def get_hist_data(data): and inside of dataframe each column name will be placed.

I want same output which has shown above but data won't be a string but a dataframe where every column name will be placed like as data['A'], data['B']...

You can access a data frame's column as a list with df[col].to_list()

def get_hist_data(data):
    histdata = []
    for col in data.columns:
        histdata.append(data[col].to_list())
    return histdata

This will return a list of sublists, where each sublist was a column in the original data .

You can do something like this:-

histdata = []
for col in data:
    df = pd.DataFrame(data[col]) 
    histdata.append(df)

for col in histdata:
    print(col)

Here histdata will contain all the dataframes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM