[英]Obtaining n number highest values in dataframe also containing strings
我有一個 dataframe ,我想在每列中找到 n 個最高的數字。 有多種方法可以做到這一點,但似乎都失敗了,因為字符串也在 dataframe 中。 我嘗試了多種方法來解決這個問題,但我總是被字符串的存在所困擾。
由於某些單元格包含%
的所有字符串類型列的一攬子遺漏將不起作用。 但是,忽略包含 AZ 的單元格會起作用。
示例 dataframe:
import pandas as pd
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']
)
一) 。 嘗試使用apply
:
test_df.apply(
lambda x: pd.Series
(x.str.strip('%').astype(float).nlargest(2).index)
)
AttributeError: ('Can only use .str accessor with string values!', 'occurred at index Squeak Appeal')
ii)。 一個)。 嘗試使用for-loop
:
headers = list(test_df.columns.values)
for header in headers:
if not ['a-z'] in test_df[header]:
max_value = (
test_df[header]
.str.strip('%') # remove the ending %
.astype(float) # convert to float
.nlargest(10).index # nlargest and index
)
TypeError: unhashable type: 'list'
ii)。 乙)。 我還嘗試排除“e”作為通過if-statement
的實驗:
#...
if not 'e' in test_df[header]:
#...
AttributeError: Can only use .str accessor with string values!
三)。 我嘗試使用numpy
,因為我在其他地方看到過使用它,但並沒有真正理解這個想法:
import numpy as np
N = 3
a = np.argsort(-test_df.values, axis=0)[-1:-1-N:-1]
b = pd.DataFrame(df.index[a], columns=df.columns)
print (b)
TypeError: bad operand type for unary -: 'str'
我可以打開 go 但我覺得這會浪費文本空間。 誰能指出我正確的方向?
示例結果:
print(richochet_chance_max)
Animal Squeak Appeal Richochet Chance
1 Turtle 1.92 30%
2 Chicken 11.40 16%
print(squeak_appeal_max)
Animal Squeak Appeal Richochet Chance
1 Otter 12.8 8%
2 Chicken 11.4 16%
您可以將字符串列轉換為float
,然后在獲得 n 個最大值后將其轉換回str
:
# Convert the string column to float
test_df['Richochet Chance'] = test_df['Richochet Chance'].str.strip('%').astype(float)
# Get nlargest as you want
test_df = test_df.nlargest(2, columns=['Squeak Appeal', 'Richochet Chance'])
# Convert the string column back to string
test_df['Richochet Chance'] = test_df['Richochet Chance'].map(lambda x: f'{x:.0f}%')
Output 對於nlargest = 2
:
Animal Squeak Appeal Richochet Chance
0 Otter 12.8 8%
2 Chicken 11.4 16%
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.