将数据框中的多个列追加到lis中

2024-04-24 08:20:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试从多个columnsimportxy coordinates到一个列表中。当coordinates从单个column读取时,我可以让它继续工作,但是很难让它高效地从多个columns读取。在

我需要这个来策划

尝试:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

d = ({
    'Time' : [1,2,3,4,5,6,7,8],       
    'GrA1_X' : [10,12,17,16,16,14,12,8],                 
    'GrA1_Y' : [10,12,13,7,6,7,8,8], 
    'GrA2_X' : [5,8,13,16,19,15,13,5],                 
    'GrA2_Y' : [6,15,12,7,8,9,10,8],
    'GrB1_X' : [15,18,25,16,6,15,17,10],                 
    'GrB1_Y' : [7,12,5,9,10,12,18,9], 
    'GrB2_X' : [10,4,18,14,16,12,17,4],                 
    'GrB2_Y' : [8,12,16,8,10,14,12,15],         
     })

df = pd.DataFrame(data=d)

GrA_X = df[df.columns[1::2][:2]]
GrA_Y = df[df.columns[2::2][:2]]

GrB_X = df[df.columns[5::2][:2]]
GrB_Y = df[df.columns[6::2][:2]]

fig = plt.figure(figsize=(10,6))
ax = plt.gca()

Zs = []
for l,color in zip('AB', ('red', 'blue')):
    # plot all of the points from a single group
    ax.plot(GrA_X.iloc[0], GrA_Y.iloc[0], '.', c='red', ms=15, label=l, alpha = 0.5)
    ax.plot(GrB_X.iloc[0], GrB_Y.iloc[0], '.', c='blue', ms=15, label=l, alpha = 0.5)    

    Zrows = []
    for _,row in df.iterrows():
        x,y = row['Gr%s_X'%l], row['Gr%s_Y'%l]

我被困在Zrows = []电话里了。具体来说,如何在这个列表中追加multiplecolumns。在


Tags: columnsimportdf列表plotaspltax
2条回答

我还不清楚我是否正确理解了上一个循环的目的,但我会冒这个风险并提出解决方案。您的问题似乎与列的命名有关,我认为除了循环使用Gr{A,B}{1,2}_{X,Y}(这里的{}表示变体)之外,没有其他方法。我将使用一个嵌套的for-循环,即:

Zs = []
for l,color in zip('AB', ('red', 'blue')):
    # plot all of the points from a single group
    ax.plot(GrA_X.iloc[0], GrA_Y.iloc[0], '.', c='red', ms=15, label=l, alpha = 0.5)
    ax.plot(GrB_X.iloc[0], GrB_Y.iloc[0], '.', c='blue', ms=15, label=l, alpha = 0.5)    

    Zrows = []
    for _,row in df.iterrows():
        for i in [1,2]:
            x,y = row['Gr{}{}_X'.format(l,i)], row['Gr{}{}_Y'.format(l,i)]
            Zrows.append((x,y))


print(Zrows)

它给出了一个坐标元组的列表:

^{pr2}$

请注意,我将字符串格式更改为format()-语法,这在我看来大大提高了可读性。请让我知道这是否接近你的目标。在

如果我能正确理解你的问题,这可能是另一种解决办法。在

df = pd.DataFrame(data=d)
X = [df[c].tolist() for c in df.columns if c.find("_X") >= 0]
Y = [df[c].tolist() for c in df.columns if c.find("_Y") >= 0]

allX = [x for sublist in X for x in sublist]
allY = [y for sublist in Y for y in sublist]

dfXY = pd.DataFrame({"X": allX, "Y":allY})

现在你在一个简单的数据帧中有了所有的x和y。 干杯

相关问题 更多 >