Home > Enterprise >  How can I permanently store a sorted version of a data frame in a new variable using pandas
How can I permanently store a sorted version of a data frame in a new variable using pandas

Time:12-14

So basically, I have a txt file from https://scipython.com/static/media/2/problems/P2.6/redwood-data.txt that lists a bunch of trees.

I want to find the one with the highest height and largest diameter. I am trying to use sort_values from python but despite the sorting, I have now discovered it doesn't modify the original dataframe from the text file which is what I am trying to achieve so I can pick the first line and display it.

Is there anyway to store the modified version in a new variable?

Here is what I am currently using:

import pandas as pd
trees = pd.read_csv('redwood_data.txt', delimiter='\t')
trees.sort_values('diameter (m)', ascending = False, inplace = True)

print("The tree with the largest diameter is", trees['Tree name'][0], "with a diameter of", trees['diameter (m)'][0], "m.")
trees.sort_values('height (m)', ascending = False, inplace = True)
print("The tree with the highest height is", trees['Tree name'][0], "with a height of", trees['height (m)'][0], "m.")

CodePudding user response:

You are most likely looking for the .idxmax method which returns the first index of the maximal item:

i = trees["diameter (m)"].idxmax()
tree, diameter = trees.at[i, "Tree name"], trees.at[i, "diameter (m)"]
print(f"The tree with the largest diameter is {tree} with a diameter of {diameter} m.")
i = trees["height (m)"].idxmax()
tree, height = trees.at[i, "Tree name"], trees.at[i, "height (m)"]
print(f"The tree with the largest height is {tree} with a height of {height} m.")

or

msg = "The tree with the largest {unit} is {tree} with a {unit} of {measure} m."
for unit in "diameter", "height":
    i = trees[f"{unit} (m)"].idxmax()
    tree, measure = trees.at[i, "Tree name"], trees.at[i, f"{unit} (m)"]
    print(msg.format(tree=tree, unit=unit, measure=measure))

Result for both versions is:

The tree with the largest diameter is Stratosphere Giant with a diameter of 5.18 m.
The tree with the largest height is Hyperion with a height of 115.61 m.
  • Related