AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题 / 76920623
Accepted
Nicko Toumbas
Nicko Toumbas
Asked: 2023-08-17 18:23:43 +0800 CST2023-08-17 18:23:43 +0800 CST 2023-08-17 18:23:43 +0800 CST

如何将 for 循环拆分为 3 个单独的数据框?

  • 772

我目前正在使用 Pandas 和 Matplotlib.pyplot 使用 python,其中我使用现有信息通过过滤数据来创建三种类型企鹅的两种不同散点图。它目前适用于 for 循环,但我想知道如何使用三个数据帧而不是循环一个数据帧来实现相同的结果。

这是我目前拥有的代码

import pandas as pd
URL= 'https://gist.githubusercontent.com/anibali/c2abc8cab4a2f7b0a6518d11a67c693c/raw/3b1bb5264736bb762584104c9e7a828bef0f6ec8/penguins.csv'
df = pd.read_csv (URL)

#Graph 1
import matplotlib.pyplot as plt
body_mass = df['body_mass_g']
bill_length = df['bill_length_mm']
species = df['species']
fig, ax = plt.subplots()
adelie = df[df['species']== 'Adelie']
chinstrap = df[df['species']== 'Chinstrap']
gentoo = df[df['species']== 'Gentoo']

data = pd.DataFrame({"Species": species, "Body Mass": body_mass, "Bill Length": bill_length})

groups = data.groupby("Species")
for name, group in groups:
    plt.plot(group["Body Mass"], group["Bill Length"], marker="o", linestyle="", label=name)
ax.set_title('Penguin measurements by species')
ax.set_xlabel('Body mass (g)')
ax.set_ylabel('Bill length (mm)')
fig.tight_layout()
plt.legend()
plt.show()

#Graph 2
df['bill_proportion'] = (df['bill_length_mm']/df['bill_depth_mm'])
bill_proportion = df['bill_proportion']
body_mass = df['body_mass_g']
bill_length = df['bill_length_mm']
bill_depth = df['bill_depth_mm']
species = df['species']
fig, ax = plt.subplots()
adelie = df[df['species']== 'Adelie']
chinstrap = df[df['species']== 'Chinstrap']
gentoo = df[df['species']== 'Gentoo']

data = pd.DataFrame({"Species": species, "Body Mass": body_mass, "Bill Proportion": bill_proportion})

groups = data.groupby("Species")
for name, group in groups:
    plt.plot(group["Body Mass"], group["Bill Proportion"], marker="o", linestyle="", label=name)
ax.set_title('Penguin proportions by species')
ax.set_xlabel('Body mass (g)')
ax.set_ylabel('Bill proportion (length/width)')
fig.tight_layout()
plt.legend()
plt.show()

它目前作为循环工作,但我希望它使用三个数据帧而不是循环,但我不确定如何实现这一点。我仍然希望所有三个数据框显示在同一个散点图中,因此它看起来与现在完全相同,但使用三个数据框

python
  • 1 1 个回答
  • 60 Views

1 个回答

  • Voted
  1. Best Answer
    some3128
    2023-08-17T19:24:19+08:002023-08-17T19:24:19+08:00

    下面的代码将数据帧分成 3 个,然后进行绘图。

    import pandas as pd
    import matplotlib.pyplot as plt
    
    #Load data
    URL= 'https://gist.githubusercontent.com/anibali/c2abc8cab4a2f7b0a6518d11a67c693c/raw/3b1bb5264736bb762584104c9e7a828bef0f6ec8/penguins.csv'
    df = pd.read_csv(URL)
    
    #Make a bill_proportion column
    df['bill_proportion'] = df.bill_length_mm / df.bill_depth_mm
    
    #Split dfs by species
    df_adelie = df.loc[df.species == 'Adelie']
    df_chinstrap = df.loc[df.species == 'Chinstrap']
    df_gentoo = df.loc[df.species == 'Gentoo']
    
    #Plot all 3
    x_column = 'body_mass_g'
    y_column = 'bill_length_mm'
    
    plt.scatter(df_adelie[x_column], df_adelie[y_column], label='Adelie')
    plt.scatter(df_chinstrap[x_column], df_chinstrap[y_column], label='Chinstrap')
    plt.scatter(df_gentoo[x_column], df_gentoo[y_column], label='Gentoo')
    plt.xlabel(x_column)
    plt.ylabel(y_column)
    plt.legend()
    plt.title(f'{x_column} vs {y_column}')
    plt.show()
    
    #Repeat process, using a different y
    x_column = 'body_mass_g'
    y_column = 'bill_proportion'
    
    plt.scatter(df_adelie[x_column], df_adelie[y_column], label='Adelie')
    plt.scatter(df_chinstrap[x_column], df_chinstrap[y_column], label='Chinstrap')
    plt.scatter(df_gentoo[x_column], df_gentoo[y_column], label='Gentoo')
    plt.xlabel(x_column)
    plt.ylabel(y_column)
    plt.legend()
    plt.title(f'{x_column} vs {y_column}')
    plt.show()
    

    代码有重复,尤其是绘图方面。您可以将一些代码放入函数中。

    在此输入图像描述 在此输入图像描述

    • 0

相关问题

  • 如何检查 Pandas DataFrame 中的所有浮点列是否近似相等或接近

  • “load_dataset”如何工作,因为它没有检测示例文件?

  • 为什么 pandas.eval() 字符串比较返回 False

  • Python tkinter/ ttkboostrap dateentry 在只读状态下不起作用

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    使用 <font color="#xxx"> 突出显示 html 中的代码

    • 2 个回答
  • Marko Smith

    为什么在传递 {} 时重载解析更喜欢 std::nullptr_t 而不是类?

    • 1 个回答
  • Marko Smith

    您可以使用花括号初始化列表作为(默认)模板参数吗?

    • 2 个回答
  • Marko Smith

    为什么列表推导式在内部创建一个函数?

    • 1 个回答
  • Marko Smith

    我正在尝试仅使用海龟随机和数学模块来制作吃豆人游戏

    • 1 个回答
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 个回答
  • Marko Smith

    为什么 'char -> int' 是提升,而 'char -> Short' 是转换(但不是提升)?

    • 4 个回答
  • Marko Smith

    为什么库中不调用全局变量的构造函数?

    • 1 个回答
  • Marko Smith

    std::common_reference_with 在元组上的行为不一致。哪个是对的?

    • 1 个回答
  • Marko Smith

    C++17 中 std::byte 只能按位运算?

    • 1 个回答
  • Martin Hope
    fbrereto 为什么在传递 {} 时重载解析更喜欢 std::nullptr_t 而不是类? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 您可以使用花括号初始化列表作为(默认)模板参数吗? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi 为什么列表推导式在内部创建一个函数? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A fmt 格式 %H:%M:%S 不带小数 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python C++20 的 std::views::filter 未正确过滤视图 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute 为什么 'char -> int' 是提升,而 'char -> Short' 是转换(但不是提升)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa 为什么库中不调用全局变量的构造函数? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis std::common_reference_with 在元组上的行为不一致。哪个是对的? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev 为什么编译器在这里错过矢量化? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan C++17 中 std::byte 只能按位运算? 2023-08-17 17:13:58 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve