如何将行元素对连接到数据帧中的新列中?

2024-04-23 16:40:01 发布

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

我有一个数据框,其中列是坐标(例如x1,y1,x2,y2…)。坐标列从第8列开始(前几列与问题无关)
我有一个更大的示例here,但这里有一个示例:

start_column = 8    
df = pd.DataFrame(columns = ['x1','y1','x2','y2'],
                 data = [(0,0,1,0),(0,1,2,3),(-1,-2,None,None)])
for i in range(7):
    df.insert(0,'c'+str(7-i),'x')
df

我想在DataFrame中创建一个新列作为xy对的列表,如:df["coordinates"]=[[x1,y1],[x2,y2],[x3,y3]....]

到目前为止我试过的:

for row in df.iterrows():
   for i in range(1,total_count_of_xy_rows):
      df["coordinates"]= 
             df[["x{}".format(i),"y{}".format(i)]].values.tolist()
   print(df)

有没有更好的办法?你知道吗


Tags: 数据innoneformat示例dataframedffor
1条回答
网友
1楼 · 发布于 2024-04-23 16:40:01

可以通过跨不同行.apply使用自定义列表理解函数来创建新列:

start_column = 8    
coordinates_list = list(zip(df.columns[(start_column-1):-1:2],df.columns[start_column::2]))
df['coordinates'] = df.apply(lambda row: [(row[x], row[y]) 
                                          for x,y in coordinates_list if not any((pd.isna(row[x]), pd.isna(row[y])))], axis=1)

使用此示例输入,坐标列从第8列开始,如您在注释中所述:

df = pd.DataFrame(columns = ['x1','y1','x2','y2'],
                 data = [(0,0,1,0),(0,1,2,3),(-1,-2,None,None)])
for i in range(start_column-1):
    df.insert(0,'c'+str(start_column-1-i),'x')
df

    c1  c2  c3  c4  c5  c6  c7  x1  y1  x2  y2
0   x   x   x   x   x   x   x   0   0   1.0 0.0
1   x   x   x   x   x   x   x   0   1   2.0 3.0
2   x   x   x   x   x   x   x   -1  -2  NaN NaN

这将产生以下输出:

c1  c2  c3  c4  c5  c6  c7  x1  y1  x2  y2  coordinates
0   x   x   x   x   x   x   x   0   0   1.0 0.0 [(0, 0), (1.0, 0.0)]
1   x   x   x   x   x   x   x   0   1   2.0 3.0 [(0, 1), (2.0, 3.0)]
2   x   x   x   x   x   x   x   -1  -2  NaN NaN [(-1, -2)]

它处理的是每一行中坐标数不等的问题。希望有帮助!你知道吗

相关问题 更多 >