Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a dataframe's name as string

I have problems converting the variable into a string. It doesn't work with str(object), this prints out the dataframe instead. I labelled my dataframe as Apple:

Apple = pd.Dataframe()

Then I was trying to do a for loop to save the the data into another dataframe. So i did it by: First, I stored the stocks in apple_stock_list, [Apple, Samsung] Then I wanted to do a for loop like this:

for stocks in apple_stock_list:
    for feature in features:
        apple_stock[str(stocks) + "_"+ feature] = stocks[feature]

However, str(stocks) does not change stocks into "Apple". Is there anyway I could get the Dataframe's variable name to be a string?

Thank you in advance!

like image 636
needsumhelp Avatar asked Nov 11 '17 10:11

needsumhelp


People also ask

How do you convert a data frame to a string?

If you want to change the data type for all columns in the DataFrame to the string type, you can use df. applymap(str) or df.

How do you convert a series data to a string in Python?

Example #1: Use Series. to_string() function to render a string representation of the given series object.

How do I convert a column into a DataFrame to a string?

Convert a Pandas Dataframe Column Values to String using map Similar to the . astype() Pandas series method, you can use the . map() method to convert a Pandas column to strings.


1 Answers

Considering the following df

import pandas as pd
import numpy as np

apple = pd.DataFrame(data=np.ones([5,5]))

As @Georgy suggests one can name the dataframe like this

apple.name = 'Apple'

Then get the string with apple.name.

[In]: print(apple.name) 
[Out]: Apple

However, assuming one wants to get the DFs from a particular label, one might as well create a dictionary with

dfdict = {'Apple': apple}

and access the dataframe via

[In]: print(dfdict['Apple'])
[Out]:
     0    1    2    3    4
0  1.0  1.0  1.0  1.0  1.0
1  1.0  1.0  1.0  1.0  1.0
2  1.0  1.0  1.0  1.0  1.0
3  1.0  1.0  1.0  1.0  1.0
4  1.0  1.0  1.0  1.0  1.0
like image 131
Gonçalo Peres Avatar answered Oct 14 '22 06:10

Gonçalo Peres