简体   繁体   English

Python - 在使用 pandas.DataFrame.append 时遇到问题

[英]Python - Having trouble with pandas.DataFrame.append

Can someone please help me figure out why the quer.append(l) is not working?有人可以帮我弄清楚为什么 quer.append(l) 不起作用吗? My query for 'quer' and 'l' seem to work correctly.我对 'quer' 和 'l' 的查询似乎工作正常。 quer returns 31 rows (all rows that are "YES" in the Hill column. And 'l' returns 9 rows (all rows that are "YES" in the Underwater column). I then try to append the two together, but that doesn't seem to be workings. The 'return quer' is just returning the 31 YES that are in the Hill column and is not appending the 'l' dataframe quer 返回 31 行(Hill 列中为“YES”的所有行。而 'l' 返回 9 行(Underwater 列中为“YES”的所有行)。然后我尝试将两者附加在一起,但这并没有'似乎不起作用。'return quer' 只是返回 Hill 列中的 31 YES 并且没有附加 'l' 数据框

CSV: https://docs.google.com/spreadsheets/d/1PjnN00bikJfY7mO3xt4nV5Ua1yOIsh8DycGqed6hWD8/edit?usp=sharing CSV: https : //docs.google.com/spreadsheets/d/1PjnN00bikJfY7mO3xt4nV5Ua1yOIsh8DycGqed6hWD8/edit? usp =sharing

Workflow: save the csv as Monsters.csv and python file in the same folder and run the python file工作流程:将 csv 保存为 Monsters.csv 和 python 文件在同一文件夹中并运行 python 文件

import pandas as pd
import os

abspath = os.path.abspath(__file__)
dname = os.path.dirname(abspath)
os.chdir(dname)

currentDir = os.getcwd()

data = pd.read_csv(r'Monsters.csv')

def biomes(biome):
        ind = 0
        for i in range(len(biome)):
            if i == 0:
                quer = data.query("{} == 'YES'".format(biome[ind]))
                print ("Hill:", quer)  # returns 31 rows
            if i > 0:
                l = data.query("{} == 'YES'".format(biome[ind]))
                quer.append(l)   #this append is not working
                print ("Underwater: ", l ) #returns 9 rows
            ind += 1
        return quer # returns 31 rows (only the Hill biome) for some reason.

print(biomes(["Hill", "Coast"]))

As per the official Pandas documentation , DataFrame.append() returns a new object - it does not modify the object it is being called on.根据官方 Pandas 文档DataFrame.append()返回一个新对象 - 它不会修改正在调用的对象。 As such, I believe your append() is creating a new DataFrame, but not assigning it anywhere.因此,我相信您的append()正在创建一个新的 DataFrame,但没有在任何地方分配它。

Try replacing quer.append(l) with quer = quer.append(l) to resolve this.尝试用quer = quer.append(l)替换quer.append(l) quer = quer.append(l)来解决这个问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM