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

标签 python pandas dataframe seaborn

当我尝试在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)

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

相关文章:

python - 分割字符串并按字长排序

python:添加到字典会出错

python - 为子域设置 SERVER_NAME 后 flask 中 www 前缀的问题

Python Pandas 对齐单元格中的文本

python - 需要使用两列纬度和经度合并两个 Pandas 数据框

python - 从 pandas DataFrame 中的日期时间列中提取月份

python - 通过关键列合并一列的中位数 - SFrame/Pandas

r - 按 R 中的模式值删除列

Python Cheetah - 为模板指定名称/值对

python - 使用常规月份顺序而不是字母顺序的交叉表后重新索引列