[英]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.