gpt4 book ai didi

python - 当 seaborn 绘制由列表组成的数据框时,pandas 返回 DataError

转载 作者:太空宇宙 更新时间:2023-11-04 02:02:00 25 4
gpt4 key购买 nike

当我尝试在 seaborn 中绘制 pandas 数据框时,出现了 DataError。我通过从字典重新创建数据框而不是使用列表和 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

正确工作的第一个解决方案是设置空 DataFramedtype:

line_df1 = pd.DataFrame(columns=['x','y'], dtype=int)

但如果性能很重要,第二种解决方案更好,因为更新空 DataFramelast 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com