【问题标题】:Python - coordinates plottingPython - 坐标绘图
【发布时间】:2021-11-11 06:37:27
【问题描述】:

我需要建议。在我的数据库中,我有 x 点和 y 点的形式:

df = pd.read_sql_table('table', cnx)
id curves
1 [(x,y),(x,y),(x,y) etc.]
2 [(x,y),(x,y),(x,y) etc.]
type(df['curves']) #pandas.core.series.Series

我想尝试绘制折线图。

我尝试了几种解决方案。但对我没有任何帮助。

data = df['curves']
plt.plot(*zip(*data))
plt.show()

data_in_array = np.array(data)
transposed = data_in_array.T
x,y = transposed #but here i got error - not enough values to unpack (expected 2, got 1)

请指教

【问题讨论】:

    标签: python pandas numpy jupyter-notebook ipython


    【解决方案1】:

    展开曲线列表列

    df = df.explode('curves').reset_index()
    

    创建单独的 x 和 y 列

    df['curves_x'] = df.curves.str[0]
    df['curves_y'] = df.curves.str[1]
    

    使用 seaborn 绘图

    import seaborn as sns
    import matplotlib.pyplot as plt
    
    sns.lineplot(data=df, x='curves_x', y='curves_y', hue='id')
    plt.show()
    

    为了更好地理解,让我们取一些样本数据,

       id                          curves
    0   1  [(10, 20), (20, 30), (30, 50)]
    1   2  [(10, 10), (20, 40), (30, 20)]
    

    分解列并重置索引

       id    curves
    0   1  (10, 20)
    1   1  (20, 30)
    2   1  (30, 50)
    3   2  (10, 10)
    4   2  (20, 40)
    5   2  (30, 20)
    

    创建 x 和 y 列

       id    curves  curves_x  curves_y
    0   1  (10, 20)        10        20
    0   1  (20, 30)        20        30
    0   1  (30, 50)        30        50
    1   2  (10, 10)        10        10
    1   2  (20, 40)        20        40
    1   2  (30, 20)        30        20
    

    剧情会是这样的

    【讨论】:

    • 感谢您的宝贵时间,但这对我不起作用。当我查看它时,我在列 curves_x[curves_y(
    • 在此之前,请确保您的 curves 列是列表类型而不是字符串。如果是字符串(似乎是这样),请使用testdf['curves'] = testdf['curves'].map(ast.literal_eval)import ast 太@Cesc
    • 当我这样做时,我得到一个错误:A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy self._set_item(key, value)
    • 使用df.loc[:, 'curves'] = df['curves'].map(ast.literal_eval)@Cesc
    • 还是一无所有 - ValueError: malformed node or string: [(0, 4.579), (0.2153549, 9.862635), (0.4196396, 9.862635), (0.6154251, 9.069808), (0.8132706, 22.54274), (1.012405, 20.9576), (1.210602, 21.57384), (1.409637, 23.24702), (1.61058, 21.92599), (1.80954, 25.53644), (2.008942, 24.9202), (2.20961, 22.63078), (2.410034, 25.36037), (2.609161, 22.63078), (2.80925, 23.33506), (2.929764, 24.48002), (3.129486, 29.58708), (3.328705, 32.22915), (3.529053, 37.3362), (3.729904, 33.28557), (3.928864, 30.82008), (4.128937, 28.79476), (4.330307, 26.50534)......]
    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 2021-06-21
    • 1970-01-01
    • 1970-01-01
    • 2017-07-14
    • 2021-10-21
    • 2020-03-01
    • 1970-01-01
    相关资源
    最近更新 更多