How to store print values in a variable in Python?

Asked

Viewed 130 times

-1

I imported data from a table in Google Sheets using Pandas and created a data frame. I renamed your columns and made a for loop to filter between one of these columns, the values below 20, however, I can only see the result with a print. Also, I cannot store these values in a variable. For example, to use them later in a graph.

I tried to create the variable before print. I tried to convert to str or in int.

from google.colab import auth
auth.authenticate_user()
import gspread
from oauth2client.client import GoogleCredentials
gc = gspread.authorize(GoogleCredentials.get_application_default())
worksheet = gc.open('CSV').sheet1
rows = worksheet.get_all_records()
import pandas as pd
tabela = pd.DataFrame.from_records(rows)
tabela.set_index((["nome","idade","pet","jardim","casada"]))
idades =tabela["idade"]

for x in idades:
    if x <=20:
        print(x)

1 answer

2


One way is to use the loc

Example:

Creating Test Dataframe

>>> df = pd.DataFrame({"idade": [18, 22, 19, 21], "nome": ["Joao", "Pedro", "Sergio", "Murilo"]})

>>> print(df)
   idade    nome
0     18    Joao
1     22   Pedro
2     19  Sergio
3     21  Murilo

Filtering

>>> df.loc[df["idade"] <= 20]
   idade    nome
0     18    Joao
2     19  Sergio

Note vc can associate the result to a new dataframe

>>> df1 = df.loc[df["idade"] <= 20]

>>> print(df1)
   idade    nome
0     18    Joao
2     19  Sergio

Using more than one condition

>>> df1 = df.loc[(df["idade"] <= 20) & (df["nome"] == "Sergio")]

>>> print(df1)
   idade    nome
2     19  Sergio

Note Note that each condition is between parentheses.

Note Use & for and, | for or and ~ for not

  • 1

    Nice, thank you so much for answering me, but is using the loop for not possible? Because I also have cases of if with two or more conditions, in which case I think this option would be interesting. Thanks

  • 1

    Updated post for more than one condition. In time: AVOID using the for in dataframes. There are several better ways with regard mainly to performance.

  • Ahh didn’t know, as you might notice, I’m new to Python! I’ll use it the way you taught me!

  • 1

    @Flavia You are learning, get in the profile of Paulo Marques and study the answers he posted on the site. he knows what he’s talking about and also research here on the website questions and answers from other authors.

  • 1

    Yeah, I’ve been doing that, doing a lot of research, it’s the first time I ask because I really didn’t know where else to look!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.