用 pandas 在空列表中追加项目

问题描述 投票:0回答:2

我正在尝试使用 Pandas 创建一个过滤后的数据框,并将其发送到使用 matplotlib 按条件分割的屏幕,但是当我尝试将项目添加到空列表中时,该列表不会按条件过滤,而是包含 csv 的所有元素.

这是代码:

from matplotlib import pyplot as plt
import pandas as pd

plt.style.use('ggplot')
df = pd.read_csv('C:/Users/Gemxs/Documents/Python/Pandas/pokemon.csv')

fig1, (Legendary, Normal) = plt.subplots(nrows=2, ncols=1)

Total = []
gen = []

Leg = df[(df['Legendary'] == True)]
TotalLeg = df['Total']
GenLeg = df['Generation']

Normal = df[(df['Legendary'] == False)]
TotalNormal = df[(df['HP'] < 500)]

for index,row in df.iterrows():
    if ([Leg['Total'] > 500]):
        Total.append(row['Total'])

print(Total)

我想仅将> 500的元素发送到空列表。

python pandas
2个回答
0
投票

你不需要循环,你可以使用 tolist 来获取列表中的值:

import pandas as pd

df = pd.read_csv('C:/Users/Gemxs/Documents/Python/Pandas/pokemon.csv')

mask = df['Total'] > 500
Total = df[mask]["Total"].tolist()

print(Total)

0
投票

您使用的循环和条件语句未正确设置来过滤这些值。让我们解决这个问题。

这是代码的修订版本:

from matplotlib import pyplot as plt
import pandas as pd

plt.style.use('ggplot')
df = pd.read_csv('C:/Users/Gemxs/Documents/Python/Pandas/pokemon.csv')

# Splitting the dataframe into Legendary and Non-Legendary Pokémon
leg_df = df[df['Legendary'] == True]
norm_df = df[df['Legendary'] == False]

# Filtering Legendary Pokémon with 'Total' greater than 500
filtered_leg = leg_df[leg_df['Total'] > 500]

# Extracting the 'Total' values to a list
total_over_500 = filtered_leg['Total'].tolist()

print(total_over_500)

在这段代码中,我:

将 DataFrame 分成两部分:一个用于传奇神奇宝贝 (leg_df),另一个用于普通神奇宝贝 (norm_df)。 过滤 Legendary DataFrame (leg_df) 以仅包含“Total”值大于 500 的 Pokémon。 将此过滤后的 DataFrame 中的“Total”列提取到列表中 (total_over_500)。 请记住,在处理 Pandas 时,使用内置过滤和列选择方法通常比使用 iterrows() 循环遍历行更有效

© www.soinside.com 2019 - 2024. All rights reserved.