如何使用python中的熊猫从数据框创建子列表

问题描述 投票:-3回答:1

outputof the dataframe I have to create the sublist from the excel which contain the xy as list

我在使用熊猫创建子列表时遇到了问题。我想在数据框中创建一列,其中包含xy对列表,例如df [“ coordinates”] = [[x1,y1],[x2,y2],[x3,y3] ....]。请协助解决这个问题。

enter code here
import csv
import pandas as pd
df = pd.read_excel("data.xlsx",index =0)
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)
python pandas
1个回答
0
投票

您可以通过.apply-跨不同行的自定义列表理解功能来创建新列:

coordinates_list = list(zip(df.columns[:-1:2],df.columns[1::2]))
df['coordinates'] = df.apply(lambda row: [(row[x], row[y]) for x,y in coordinates_list], axis=1)
© www.soinside.com 2019 - 2024. All rights reserved.