假设我有以下数据框:
A | B
1 | Ms
1 | PhD
2 | Ms
2 | Bs
我想删除关于 A 列的重复行,并且我想保留 B 列中值为“PhD”的行作为原始行,如果我找不到“PhD”,我想保留该行B 列中的“Bs”。
我正在尝试使用
df.drop_duplicates('A')
有条件
原文由 Rakesh Adhikesavan 发布,翻译遵循 CC BY-SA 4.0 许可协议
假设我有以下数据框:
A | B
1 | Ms
1 | PhD
2 | Ms
2 | Bs
我想删除关于 A 列的重复行,并且我想保留 B 列中值为“PhD”的行作为原始行,如果我找不到“PhD”,我想保留该行B 列中的“Bs”。
我正在尝试使用
df.drop_duplicates('A')
有条件
原文由 Rakesh Adhikesavan 发布,翻译遵循 CC BY-SA 4.0 许可协议
考虑使用 Categoricals
。他们很好的是按非字母顺序(除其他外)对文本进行分组/排序。
import pandas as pd
#create a pandas dataframe for testing with two columns A integer and B string
df = pd.DataFrame([(1, 'Ms'), (1, 'PhD'),
(2, 'Ms'), (2, 'Bs'),
(3, 'PhD'), (3, 'Bs'),
(4, 'Ms'), (4, 'PhD'), (4, 'Bs')],
columns=['A', 'B'])
print("Original data")
print(df)
# force the column's string column B to type 'category'
df['B'] = df['B'].astype('category')
# define the valid categories:
df['B'] = df['B'].cat.set_categories(['PhD', 'Bs', 'Ms'], ordered=True)
#pandas dataframe sort_values to inflicts order on your categories
df.sort_values(['A', 'B'], inplace=True, ascending=True)
print("Now sorted by custom categories (PhD > Bs > Ms)")
print(df)
# dropping duplicates keeps first
df_unique = df.drop_duplicates('A')
print("Keep the highest value category given duplicate integer group")
print(df_unique)
印刷:
Original data
A B
0 1 Ms
1 1 PhD
2 2 Ms
3 2 Bs
4 3 PhD
5 3 Bs
6 4 Ms
7 4 PhD
8 4 Bs
Now sorted by custom categories (PhD > Bs > Ms)
A B
1 1 PhD
0 1 Ms
3 2 Bs
2 2 Ms
4 3 PhD
5 3 Bs
7 4 PhD
8 4 Bs
6 4 Ms
Keep the highest value category given duplicate integer group
A B
1 1 PhD
3 2 Bs
4 3 PhD
7 4 PhD
原文由 mattvivier 发布,翻译遵循 CC BY-SA 4.0 许可协议
2 回答5.2k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
2 回答869 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
使用自定义函数对数据框进行排序:
我们的排序功能:
cmp = lambda x:2 if 'PhD' in x else 1 if 'Bs' in x else 0
在行动中:
sort_df(df,'B',cmp).drop_duplicates('A', take_last=True)
PS 在现代熊猫版本中没有选项take_last
,使用keep
代替 - 请参阅文档。