简体   繁体   中英

Retrieve information from a specific row of a pandas dataframe

Is there a cleaner way to retrieve the info from a specific row (in my case from the last one) other than filtering the necessary row + using iterrows?

df = pd.DataFrame({'some_info_1': [11, 12, 13, 14],
                   'some_info_2': [21, 22, 23, 24],
                   'some_info_3': [31, 32, 33, 34]})
    
    # retrieve the last row and apply itterrows
    for index, row in df.iloc[-1:].iterrows():
        # retrieve specific column values of the last row
        last_row_some_info_1 = row["some_info_1"]
        last_row_some_info_2 = row["some_info_2"]
        last_row_some_info_3 = row["some_info_3"]

        print(last_row_some_info_1)
        print(last_row_some_info_2)
        print(last_row_some_info_3)

output:

14
24
34

The solution offered by @adir abargil doesn't seem to be quite efficient if we need multiple column values, since it means that in that case, we would have to retrieve the same row multiple times.

Also, the following approach would not work, as the "test_row" in this case will point to a dataframe containing the last row but not the row itself. Therefore the output would not be the same:

test_row = df.iloc[-1:]
print(test_row["some_info_1"])

output:

3    14
Name: some_info_1, dtype: int64

Regards,

UPDATE 20201118: Added sample input with the expected output UPDATE 20201120: Added a sample of retrieving the value directly from df.iloc[-1:]

Did you mean this?

specific =df.iloc[-1]["col_name"] 

update according to comment:

if you want to avoid calling df.iloc[-1] many time just save it as variable:

row = df.iloc[-1]
specific1 = row['col_1']
specific2 = row['col_2']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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