[英]How to sort each row of pandas dataframe and return column index based on sorted values of row
我正在嘗試對熊貓數據框的每一行進行排序,並獲取新數據框中排序值的索引。 我可以用很慢的方式做。 誰能為此建議使用並行化或矢量化代碼進行改進。 我在下面發布了一個示例。
data_url =' https: //raw.githubusercontent.com/resbaz/r-novice-gapminder-files/master/data/gapminder-FiveYearData.csv'
# read data from url as pandas dataframe
gapminder = pd.read_csv(data_url)
# drop categorical column
gapminder.drop(['country', 'continent'], axis=1, inplace=True)
# print the first three rows
print(gapminder.head(n=3))
year pop lifeExp gdpPercap
0 1952 8425333.0 28.801 779.445314
1 1957 9240934.0 30.332 820.853030
2 1962 10267083.0 31.997 853.100710
我正在尋找的結果是這個
tag_0 tag_1 tag_2 tag_3
0 pop year gdpPercap lifeExp
1 pop year gdpPercap lifeExp
2 pop year gdpPercap lifeExp
在這種情況下,由於pop
始終高於gdpPercap
和lifeExp
,因此它始終排在第一位。
通過使用以下代碼,我可以實現所需的輸出。 但是,如果df
有很多行/列,則計算會花費更長的時間。
誰能建議對此進行改進
def sort_df(df):
sorted_tags = pd.DataFrame(index = df.index, columns = ['tag_{}'.format(i) for i in range(df.shape[1])])
for i in range(df.shape[0]):
sorted_tags.iloc[i,:] = list( df.iloc[i, :].sort_values(ascending=False).index)
return sorted_tags
sort_df(gapminder)
這可能和numpy一樣快:
def sort_df(df):
return pd.DataFrame(
data=df.columns.values[np.argsort(-df.values, axis=1)],
columns=['tag_{}'.format(i) for i in range(df.shape[1])]
)
print(sort_df(gapminder.head(3)))
tag_0 tag_1 tag_2 tag_3
0 pop year gdpPercap lifeExp
1 pop year gdpPercap lifeExp
2 pop year gdpPercap lifeExp
說明: np.argsort
沿行對值進行排序,但返回對數組進行排序的索引,而不是對數組進行排序的索引。 減號按降序排列。 在您的情況下,您可以使用索引對列進行排序。 numpy廣播負責返回正確的形狀。
對於您的示例,運行時間約為3毫秒,而函數運行時約為2.5毫秒。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.