当我尝试在seaborn中绘制pandas数据框时,我遇到了数据错误。我通过从字典重新创建数据帧而不是使用列表和 for 循环来解决这个问题。但是,我仍然不明白为什么在第一种情况下会出现错误。这两个数据框对我来说看起来相同。有人可以解释一下这里发生了什么吗?
# When I create two seemingly identical data frames.
x = [0, 1, 2]
y = [3, 5, 7]
line_df1 = pd.DataFrame(columns=['x','y'])
for i in range(3):
line_df1.loc[i] = [x[i], y[i]]
line_dict = {'x': [0, 1, 2], 'y': [3, 5, 7]}
line_df2 = pd.DataFrame(line_dict)
# they look identical when printed
print(line_df1)
print(line_df2)
>> x y
>> 0 0 3
>> 1 1 5
>> 2 2 7
>> x y
>> 0 0 3
>> 1 1 5
>> 2 2 7
# This first one throws a DataError...
sns.lineplot('x', 'y', data=line_df1)
# ..but this one does not.
sns.lineplot('x', 'y', data=line_df2)
最佳答案
问题是第一个值是对象,由 DataFrame.dtypes
验证:
print(line_df1.dtypes)
x object
y object
dtype: object
print(line_df2.dtypes)
x int64
y int64
dtype: object
正确工作的第一个解决方案的解决方案是将dtype
设置为空DataFrame
:
line_df1 = pd.DataFrame(columns=['x','y'], dtype=int)
但是如果性能很重要,那么第二种解决方案更好,因为更新空 DataFrame
是 last instance :
6) updating an empty frame (e.g. using loc one-row-at-a-time)
关于python - 当seaborn绘制由列表组成的数据框时,pandas返回DataError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55515115/