
本文档旨在指导读者如何利用 Pandas 的 groupby 和 merge 功能,将一个数据帧中的值映射到另一个数据帧,并检查特定个体是否包含了目标词汇。通过交叉连接创建所有可能的组合,并使用左连接和填充缺失值,最终生成包含完整信息的汇总数据帧。
首先,确保你已经安装了 Pandas 库。如果没有安装,可以使用 pip 进行安装:
pip install pandas
为了演示,我们创建两个 Pandas 数据帧:df 包含每个人的词汇选择和对应计数,word_df 包含一个完整的词汇列表。
import pandas as pd
df = pd.DataFrame({
'person': [1, 1, 1, 2, 3, 4, 4, 4, 4],
'word': ['apple', 'orange', 'pear', 'apple', 'grape', 'orange', 'apple', 'pear', 'berry'],
'count': [1, 1, 1, 1, 1, 1, 1, 1, 1]
})
word_list = ['apple', 'orange', 'pear', 'berry', 'grape']
word_df = pd.DataFrame({'word': word_list})我们的目标是创建一个新的数据帧,其中包含每个人和词汇列表中所有词汇的组合,并标记出每个人实际选择的词汇(count 为 1)和未选择的词汇(count 为 0)。
首先,我们需要创建一个包含所有 person 和 word 组合的数据帧。这可以通过 merge 函数的 how='cross' 参数来实现,它执行一个交叉连接。
all_person_word_combos = word_df.merge(df['person'].drop_duplicates(), how='cross')
这行代码将 word_df (包含所有词汇) 和 df['person'].drop_duplicates() (包含所有不重复的人员ID) 进行交叉连接,生成一个包含所有可能的人员和词汇组合的数据帧。
接下来,我们将上一步创建的组合数据帧与原始数据帧 df 进行左连接。这样,如果某个 person 选择了某个 word,那么对应的 count 值将被填充;否则,count 值将为 NaN。
final_result = (
all_person_word_combos.
merge(df,
how='left',
on=['word', 'person'])
)这里,how='left' 指定了左连接,on=['word', 'person'] 指定了连接的键。
最后,我们需要将 NaN 值替换为 0,并按照 person 和 word 进行排序。
final_result = final_result.fillna(0).sort_values(['person','word'])
fillna(0) 将所有 NaN 值替换为 0,表示该 person 没有选择对应的 word。 sort_values(['person','word']) 按照 person 和 word 列对结果进行排序,使结果更易于阅读。
import pandas as pd
df = pd.DataFrame({
'person': [1, 1, 1, 2, 3, 4, 4, 4, 4],
'word': ['apple', 'orange', 'pear', 'apple', 'grape', 'orange', 'apple', 'pear', 'berry'],
'count': [1, 1, 1, 1, 1, 1, 1, 1, 1]
})
word_list = ['apple', 'orange', 'pear', 'berry', 'grape']
word_df = pd.DataFrame({'word': word_list})
all_person_word_combos = word_df.merge(df['person'].drop_duplicates(), how='cross')
final_result = (
all_person_word_combos.
merge(df,
how='left',
on=['word', 'person']).
fillna(0).
sort_values(['person','word'])
)
print(final_result)最终的结果数据帧 final_result 包含了每个人和词汇列表中所有词汇的组合,以及对应的 count 值(0 或 1),清晰地展示了每个人选择了哪些词汇。
上述方法在数据量较小时表现良好。如果数据量很大,性能可能会成为瓶颈。可以考虑使用其他优化技术,例如使用 set_index 和 reindex 来提高性能。
本文介绍了如何使用 Pandas 的 groupby 和 merge 功能,将一个数据帧中的值映射到另一个数据帧,并检查特定个体是否包含了目标词汇。通过交叉连接、左连接和填充缺失值,我们可以生成包含完整信息的汇总数据帧。这种方法在数据分析和处理中非常有用,可以帮助我们更好地理解和利用数据。
以上就是使用 Pandas Groupby 和 Merge 实现数据帧的值映射的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号