我在 pandas DataFrames 中发现了我不理解的行为。
df = pd.DataFrame(np.random.randint(1, 10, (3, 3)), index=['one', 'one', 'two'], columns=['col1', 'col2', 'col3'])
new_data = pd.Series({'col1': 'new', 'col2': 'new', 'col3': 'new'})
df.iloc[0] = new_data
# resulting df looks like:
# col1 col2 col3
#one new new new
#one 9 6 1
#two 8 3 7
但如果我尝试添加字典,我会得到以下结果:
new_data = {'col1': 'new', 'col2': 'new', 'col3': 'new'}
df.iloc[0] = new_data
#
# col1 col2 col3
#one col2 col3 col1
#one 2 1 7
#two 5 8 6
为什么会发生这种情况?在写这个问题的过程中,我意识到 df.loc 很可能只是从 new_data 中获取键,这也解释了为什么这些值是乱序的。但是,话又说回来,为什么会这样呢?如果我尝试从字典创建 DataFrame,它会像处理列一样处理键:
pd.DataFrame([new_data])
# col1 col2 col3
#0 new new new
为什么这不是 df.loc 中的默认行为?