行比较和按列追加循环

时间:2019-05-21 22:05:37

标签: python pandas loops

我有很多学校数据,我将它们保存在每月测试分数的主列表中。每当孩子得分时,“年龄”,“得分”,“学校”都会更新,我会在新行中插入更新后的数据,并跟踪所有更改。我试图找出一个python脚本来做到这一点,但是由于我是新手,所以我会不断遇到问题。

我尝试编写一个循环,但是不断出现错误,包括“ False”,“系列的真值不明确”,“元组索引必须是整数,而不是str”

master_df = pd.DataFrame({'ID': ['A', 'B', 'C', 'D'],
             'Age':[15,14,17,13],
             'School':['AB', 'CD', 'EF', 'GH'],
             'Score':[80, 75, 62, 100],
             'Date': ['3/1/2019', '3/1/2019', '3/1/2019', '3/1/2019']})

updates_df = pd.DataFrame({'ID': ['A', 'B', 'C', 'D'],
             'Age':[16,14,17,13],
             'School':['AB', 'ZX', 'EF', 'GH'],
             'Score':[80, 90, 62, 100],
             'Date': ['4/1/2019', '4/1/2019', '4/1/2019', '4/1/2019']})

# What I am trying to get is:  

updated_master = pd.DataFrame({'ID': ['A', 'A', 'B', 'B', 'C','D'],
             'Age':[15,16,14,14,17,13],
             'School':['AB', 'AB', 'CD', 'ZX', 'EF', 'GH'],
             'Score':[80, 80, 75, 90, 62, 100],
             'Date': ['3/1/2019', '4/1/2019', '3/1/2019', '4/1/2019', '3/1/2019', '3/1/2019']})

temp_delta_list = []
m_score = master_df.iloc[1:, master_df.columns.get_loc('Score')]
m_age = master_df.iloc[1:, master_df.columns.get_loc('Age')]
m_school = master_df.iloc[1:, master_df.columns.get_loc('School')]

u_score = updates_df.iloc[1:, updates_df.columns.get_loc('Score')]
u_age = updates_df.iloc[1:, updates_df.columns.get_loc('Age')]
u_school = updates_df.iloc[1:, updates_df.columns.get_loc('School')]



for i in updates_df['ID'].values:
    updated_temp_score = updates_df[updates_df['ID'] == i], u_score
    updated_temp_age = updates_df[updates_df['ID'] == i], u_age
    updated_temp_school = updates_df[updates_df['ID'] == i], u_school


    master_temp_score = master_df[master_df['ID'] == i], m_score
    master_temp_age = master_df[master_df['ID'] == i], m_age
    master_temp_school = updates_df[master_df['ID'] == i], m_school

if (updated_temp_score == master_temp_score) | (updated_temp_age == master_temp_age) | (updated_temp_school == master_temp_school):
   pass
else:
   temp_deltas = updates_df[(updates_df['ID'] == i)]
   temp_delta_list.append(temp_deltas)

我最终希望让循环比较每个ID的每个行值,并返回有任何区别的行,然后附加master_df

0 个答案:

没有答案