簡體   English   中英

查找 pandas dataframe 列的 n 個最大值(當字符串時)

[英]Finding the n maximum values (when strings) of pandas dataframe column

我試圖在我的 dataframe 中找到列的最大值。 但是,由於值包含%它們是字符串,而不是整數,這使我無法使用nlargest 我想知道是否可以將字符串轉換為整數。

這是我的代碼示例:

import pandas as pd
import re
test_data = {
            'Animal': ['Otter', 'Turtle', 'Chicken'],
            'Squeak Appeal': [12.8, 1.92, 11.4],
            'Richochet Chance': ['8%', '30%', '16%'],
            }        
test_df = pd.DataFrame(
                        test_data, 
                        columns=[ 'Animal', 'Squeak Appeal','Richochet Chance']
                        )

我嘗試使用 nlargest:

r_chance = test_df.nlargest(2, ['Richochet Chance'])
# TypeError: Column 'Richochet Chance' has dtype object, cannot use method 'nlargest' with this dtype
r_chance = test_df.nlargest(2, re.sub("[^0-9]", ""(['Richochet Chance'])))
# TypeError: 'str' object is not callable

如果沒有明智的方法來做到這一點,我不會繼續否認。 我只是想知道是否可以避免循環遍歷一個大的 df 並將字符串轉換為多個列的整數。

讓我們將該列轉換為浮點數並提取頂部索引:

idx = (test_df['Richochet Chance']
          .str.strip('%')          # remove the ending %
          .astype(float)           # convert to float 
          .nlargest(2).index       # nlargest and index
      )
test_df.loc[idx]

Output:

    Animal  Squeak Appeal Richochet Chance
1   Turtle           1.92              30%
2  Chicken          11.40              16%

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM