pandas-ai 라이브러리의 prompt를 활용하여, API KEY 없이 결과 얻는 방법

2023. 5. 23. 18:26관심있는 주제/ChatGPT Prompt

728x90

https://github.com/gventuri/pandas-ai

 

GitHub - gventuri/pandas-ai: Pandas AI is a Python library that integrates generative artificial intelligence capabilities into

Pandas AI is a Python library that integrates generative artificial intelligence capabilities into Pandas, making dataframes conversational - GitHub - gventuri/pandas-ai: Pandas AI is a Python libr...

github.com

 

 

pandasai라고 하는 라이브러리가 나와서 간단하게 어떻게 돌아가는지 궁금해서, 코드를 보면서 진행해 봤다.

 

일단 pandasai라고 하는 것은 python의 pandas dataframe의 데이터에 Prompt를 입력해서, 원하는 분석 결과를 얻을 수 있게 해주는 라이브러리이다.

 

일단 이런 것을 보면서, 분석가의 영역도 많이 대체될 수 있겠다는 생각이 들었다.

 

일단 코드를 하나씩 뜯어보니 이런 코드를 통해서 결과를 얻는 것 같다.

 

여기에 오늘 날짜나 데이터의 대한 정보를 물어보고, 이걸 코드로 바꿔주라는 지식으로 LLM에게 요청하게 된다.

 

나는 돈 없는 직장인이기 때문에, 돈을 아끼고 싶었고, 결국 LLM은 어떻게 작성하는지가 가장 중요하기 때문에

pandasai 코드에서 지시문만 가지고 와서 코드를 얻을 수 있는지 살펴봤다.

구조

지시문

_task_instruction: str = """
Today is {today_date}.
You are provided with a pandas dataframe (df) with {num_rows} rows and {num_columns} columns.
This is the result of `print(df.head({rows_to_display}))`:
{df_head}.

When asked about the data, your response should include a python code that describes the dataframe `df`.
Using the provided dataframe, df, return the python code and make sure to prefix the requested python code with {START_CODE_TAG} exactly and suffix the code with {END_CODE_TAG} exactly to get the answer to the following question:
"""

PROMPT

예를 들어 다음과 같은 prompt가 있다고 하자.

Which are the 5 happiest countries?

 

그래서 내가 이걸 지시문과 prompt를 합쳐서 물어보니, 코드만 봤을 때는 동일한 대답을 얻을 수 있었다.

결과

 

pandasai 코드 및 결과

import pandas as pd
from pandasai import PandasAI

# Sample DataFrame
df = pd.DataFrame(
    {
        "country": [
            "United States",
            "United Kingdom",
            "France",
            "Germany",
            "Italy",
            "Spain",
            "Canada",
            "Australia",
            "Japan",
            "China",
        ],
        "gdp": [
            19294482071552,
            2891615567872,
            2411255037952,
            3435817336832,
            1745433788416,
            1181205135360,
            1607402389504,
            1490967855104,
            4380756541440,
            14631844184064,
        ],
        "happiness_index": [6.94, 7.16, 6.66, 7.07, 6.38, 6.4, 7.23, 7.22, 5.87, 5.12],
    }
)

# Instantiate a LLM
from pandasai.llm.openai import OpenAI

llm = OpenAI(api_token="sk-#")

pandas_ai = PandasAI(llm, conversational=False)
pandas_ai(df, prompt="Which are the 5 happiest countries?",show_code=True)
# Import pandas library
import pandas as pd

# Create dataframe
data = {'country': ['United Kingdom', 'France', 'Germany', 'United States', 'Italy'],
        'gdp': [2411255037952, 6889389026, 7943438637, 1319314158, 633870463],
        'happiness_index': [7.16, 6.38, 7.07, 6.38, 6.66]}
df = pd.DataFrame(data)

# Sort dataframe by happiness index in descending order
df_sorted = df.sort_values(by='happiness_index', ascending=False)

# Get the top 5 happiest countries
top_5_happiest = df_sorted.head(5)['country']

print(top_5_happiest)

chatgpt 웹에서 물어본 결과

question

Today is 2023-05-22.
You are provided with a pandas dataframe (df) with {num_rows} rows and {num_columns} columns.
This is the result of `print(df.head({5}))`:
'          country             gdp  happiness_index\n0   United States  19294482071552             6.94\n1  United Kingdom   2891615567872             7.16\n2          France   2411255037952             6.66\n3         Germany   3435817336832             7.07\n4           Italy   1745433788416             6.38'.

When asked about the data, your response should include a python code that describes the dataframe `df`.
Using the provided dataframe, df, return the python code and make sure to prefix the requested python code with <startCode>  exactly and suffix the code with <endCode> exactly to get the answer to the following question:
"Which are the 5 happiest countries?"

Answer

 

<startCode>
import pandas as pd
data = {'country': ['United States', 'United Kingdom', 'France', 'Germany', 'Italy'],
'gdp': [19294482071552, 2891615567872, 2411255037952, 3435817336832, 1745433788416],
'happiness_index': [6.94, 7.16, 6.66, 7.07, 6.38]}

df = pd.DataFrame(data)

top_5_happiest_countries = df.nlargest(5, 'happiness_index')['country']

top_5_happiest_countries
<endCode>

The code above describes the dataframe df and retrieves the 5 happiest countries based on the 'happiness_index' column. The result will be a Series object containing the names of the top 5 happiest countries.

추가 테스트 진행 결과 공유

  • 한글로 물어봐도 잘 대답함(칼럼명은 잘 써줘야 함)

추가 꿀팁

웹에서는 텍스트와 같이 나와 깨지는 문제가 발생함.

그럴 땐 startCode와 End Code를 ``` 으로 바꿔서 하면 됨.

Today is 2023-05-22.
You are provided with a pandas dataframe (df) with {num_rows} rows and {num_columns} columns.
This is the result of `print(df.head({5}))`:
'          country             gdp  happiness_index\n0   United States  19294482071552             6.94\n1  United Kingdom   2891615567872             7.16\n2          France   2411255037952             6.66\n3         Germany   3435817336832             7.07\n4           Italy   1745433788416             6.38'.

When asked about the data, your response should include a python code that describes the dataframe `df`.
Using the provided dataframe, df, return the python code and make sure to prefix the requested python code with ```  exactly and suffix the code with ``` exactly to get the answer to the following question:
"Which are the 5 happiest countries?"

결과물

 

 

 

 

코드들을 자세히 보면, 다음과 같은 기능들이 있다.

1. prompt 결과물에 대한 코드 추출 기능

2. 코드를 깔끔하게 다듬는 기능(import나 df 중복 제거)

3. 코드를 실행하는 기능 (python package 사용)

결론

여러번 해보니, 항상 같은 결과만 나오는 것은 아니었고, 설정값을 좀 더 추가해 주면 같은 코드가 나오게 할 수 있지 않을까 싶다.

복잡한 그림을 요청해서 그런지 몰라도 한글로 하게 되면, 생각보다 원하는 코드가 잘 안나왔음. (prompt 문제일 가능성이 큼)

 

혹시 조금이라도 돈을 아끼고 싶은 사람은 이런 식으로 활용하시면 될 것 같다. :)

 

 

728x90