我有两个独立的数据框,它们共享一个项目编号。在 type_df
中,项目号是索引。在 time_df
中,项目编号是一列。我想计算 type_df
中 Project Type
为 2
的行数。我正在尝试使用 pandas.merge()
来做到这一点。它在使用两列时效果很好,但不是索引。我不确定如何引用索引以及 merge
是否是正确的方法。
import pandas as pd
type_df = pd.DataFrame(data = [['Type 1'], ['Type 2']],
columns=['Project Type'],
index=['Project2', 'Project1'])
time_df = pd.DataFrame(data = [['Project1', 13], ['Project1', 12],
['Project2', 41]],
columns=['Project', 'Time'])
merged = pd.merge(time_df,type_df, on=[index,'Project'])
print merged[merged['Project Type'] == 'Type 2']['Project Type'].count()
错误:
Name 'Index' is not defined.
期望的输出:
2
最佳答案
如果要在合并中使用索引,则必须指定 left_index=True
或 right_index=True
,然后使用 left_on
或 right_on
。对你来说,它应该是这样的:
merged = pd.merge(type_df, time_df, left_index=True, right_on='Project')
关于python - 在 Pandas 中使用合并列和索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31528819/