问题
Pandas似乎支持使用df.loc
将字典分配给行条目,如下所示:
df = pd.DataFrame(columns = ['a','b','c'])
entry = {'a':'test', 'b':1, 'c':float(2)}
df.loc[0] = entry
正如预期的那样,Pandas根据字典键将字典值插入到相应的列中。打印结果如下:
a b c
0 test 1 2.0
然而,如果您覆盖相同的条目,Pandas将分配字典键而不是字典值。打印此内容如下:
a b c
0 a b c
问题
为什么会发生这种情况?
具体来说,为什么这种情况只会在第二次分配时发生?所有后续的分配都会恢复到原始结果,包含(几乎)预期值:
a b c
0 test 1 2
我说“几乎”是因为对于所有后续的结果,c
上的 dtype
实际上是一个 object
而不是 float
。
我已经确定,只要涉及到字符串和浮点数,就会出现这种情况。如果只涉及字符串和整数,或整数和浮点数,就不会出现这种行为。
示例代码
df = pd.DataFrame(columns = ['a','b','c'])
print(f'empty df:\n{df}\n\n')
entry = {'a':'test', 'b':1, 'c':float(2.3)}
print(f'dictionary to be entered:\n{entry}\n\n')
df.loc[0] = entry
print(f'df after entry:\n{df}\n\n')
df.loc[0] = entry
print(f'df after second entry:\n{df}\n\n')
df.loc[0] = entry
print(f'df after third entry:\n{df}\n\n')
df.loc[0] = entry
print(f'df after fourth entry:\n{df}\n\n')
这会产生以下打印输出:
empty df:
Empty DataFrame
Columns: [a, b, c]
Index: []
dictionary to be entered:
{'a': 'test', 'b': 1, 'c': float(2)}
df after entry:
a b c
0 test 1 2.0
df after second entry:
a b c
0 a b c
df after third entry:
a b c
0 test 1 2
df after fourth entry:
a b c
0 test 1 2
pandas
版本1.2.4
上,所有 后续的数据框都具有值a b c
,而不仅仅是第二个数据框。 - aneroidpd.Series()
中,@aneroid? - rudolfovicdf.loc[0] = entry.values()
也可以工作,但这又是一个解决方法。只有在分配给新行时才能正常工作。 - aneroid1.1.5
中可以复现,因此在1.1.5
和1.2.4
之间某处进行了更改。 - DeepSpace