gpt4 book ai didi

python - 用德语 Umlaute 对 Pandas 数据框进行排序

转载 作者:太空宇宙 更新时间:2023-11-03 15:32:08 28 4
gpt4 key购买 nike

我有一个数据框,我想通过一列上的 sort_values 对其进行排序。

问题是单词的第一个字母是德语元音变音。

如 Österreich、Zürich。

它将分拣到苏黎世,Österreich。应该是在 Österreich, Zürich 分拣。

Ö 应该在 N 和 O 之间。

我已经找到了如何使用 locale 和 strxfrm 在 python 中对列表执行此操作。我能以某种方式直接在 pandas 数据框中执行此操作吗?

编辑:谢谢。 Stef 示例工作得很好,不知何故,我有 Numbers,其中他的 Version 不适用于我现实生活中的 Dataframe 示例,所以我使用了 alexey 的想法。我做了以下,也许你可以缩短这个..:


df = pd.DataFrame({'location': ['Österreich','Zürich','Bern', 254345],'code':['ö','z','b', 'v']})

#create index as column for joining later
df = df.reset_index(drop=False)

#convert int to str
df['location']=df['location'].astype(str)

#sort by location with umlaute
df_sort_index = df['location'].str.normalize('NFD').sort_values(ascending=True).reset_index(drop=False)

#drop location so we dont have it in both tables
df = df.drop('location', axis=1)

#inner join on index
new_df = pd.merge(df_sort_index, df, how='inner', on='index')

#drop index as column
new_df = new_df.drop('index', axis=1)

最佳答案

您可以将 sorted 与区域设置感知排序函数一起使用(在我的示例中,setlocale 返回 'German_Germany.1252')对列值。 棘手的部分是相应地对所有其他列进行排序。一个有点棘手的解决方案是临时将索引设置为要排序的列,然后重新索引正确排序的索引值并重置索引。

import functools
import locale
locale.setlocale(locale.LC_ALL, '')
df = pd.DataFrame({'location': ['Österreich','Zürich','Bern'],'code':['ö','z','b']})

df = df.set_index('location')
df = df.reindex(sorted(df.index, key=functools.cmp_to_key(locale.strcoll))).reset_index()

打印输出(df):

     location code
0 Bern b
1 Österreich ö
2 Zürich z


混合类型列的更新如果要排序的列是混合类型(例如字符串和整数),那么您有两种可能性:

a) 将列转换为字符串,然后按上面写的排序(结果列将全部为字符串):

locale.setlocale(locale.LC_ALL, '')
df = pd.DataFrame({'location': ['Österreich','Zürich','Bern', 254345],'code':['ö','z','b','v']})
df.location=df.location.astype(str)
df = df.set_index('location')
df = df.reindex(sorted(df.index, key=functools.cmp_to_key(locale.strcoll))).reset_index()
print(df.location.values)
# ['254345' 'Bern' 'Österreich' 'Zürich']

b) 对转换为字符串的列的副本进行排序(结果列将保留混合类型)

locale.setlocale(locale.LC_ALL, '')
df = pd.DataFrame({'location': ['Österreich','Zürich','Bern', 254345],'code':['ö','z','b','v']})
df = df.set_index(df.location.astype(str))
df = df.reindex(sorted(df.index, key=functools.cmp_to_key(locale.strcoll))).reset_index(drop=True)
print(df.location.values)
# [254345 'Bern' 'Österreich' 'Zürich']

关于python - 用德语 Umlaute 对 Pandas 数据框进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57361637/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com