csv 如何使用Pandas从DataFrame中找到正确的信息?

lp0sw83n  于 2023-05-11  发布在  其他
关注(0)|答案(1)|浏览(175)

我想知道如何使用pandas方法来弄清楚如何实现注解行中的指令。我已经尝试了几种不同的东西,但我通常最终会变得更加困惑,并删除代码后。我是一个初学者,这是我的第一个Pandas项目。
基本上,我需要计算纽约市的树木总数,纽约市特定类型的树木数量,然后计算所有行政区的树木数量。我知道我没有提供所有的信息,但我希望有一个新的方法来解决这个问题,因为我有点迷路了。(数据从CSV拉入df)

def formatInfo(matched_trees):
    for x in matched_trees:
        print(f"Entry: {x}")
        total=0
        for tree in Tree_data['spc_common']:
            if x==tree:
                total+=1
        print(f"Total number of trees:{total} ")
    
        #Needs to print percentage of matched tree of all trees in NYC. Also print percentages corresponding to each borough.

我尝试遍历数据框中的每一行,但我不知道如何获取与树种相关的其他信息。我试过实施我在网上找到的多种方法,但都没有成功。
示例输入和输出:sample

z9ju0rcb

z9ju0rcb1#

如果你的'matched_trees'是一个列表,你可以做以下事情:

specs = set(Tree_data['spc_common'].unique())
matched_tree_counts = {spec: matched_trees.count(spec) for spec in specs}
for spec, count in matched_tree_counts:
    print("{}% of matched trees are {}".format(count/len(matched_trees)*100:.2f, spec)

相关问题