0

Actually, I am facing the problem to add the data in the subcolumn in the specific format. I have created the "Polypoints" as the main column and I want

df["Polypoints"] = [{"__type":"Polygon","coordinates":Row_list}]

where Row_list is the column of dataframe which contains the data in the below format

df["Row_list"] = [[x1,y1],[x2,y2],[x3,y3]
                 [x1,y1],[x2,y2],[x3,y3]
                 [x1,y1],[x2,y2],[x3,y3]]

I want to convert the dataframe into json in the format "Polypoints" :{"__type":"Polygon" ,"coordinates":Row_list}

Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83
A.D
  • 135
  • 6
  • I have added the list in the Dataframe column "Row_list" – A.D Sep 26 '19 at 04:41
  • I have to add one more column "Polypoints" in the Dataframe as specified above and add the data of Row_list column in the "coordinates" subcolumn. – A.D Sep 26 '19 at 04:42
  • 1
    Try the `json` or `jsonpickle` packages. E.g. `json.dumps(df)`. – André Müller Sep 26 '19 at 04:50
  • Base on the question https://stackoverflow.com/questions/58091927/how-to-concatenate-pairs-of-row-elements-into-a-new-column-in-a-pandas-dataframe I have issue related to the above answer. Please check the link and suggest for the issue – A.D Sep 26 '19 at 04:58
  • Did you try `json` like proposed in comment above? It sounds to me like a good option... – Itamar Mushkin Sep 26 '19 at 05:53
  • before json I have to create one column in the dataframe "Polypoint" specified in the above format – A.D Sep 26 '19 at 06:01
  • The DataFrame Column "Polypoints" once created in the specific format then it is easier to directly get the json file. – A.D Sep 26 '19 at 06:05
  • try `df['Polypoints'] = df.apply(lambda row: {"__type":"Polygon", "coordinates":row['Row_list']} ,axis=1)` – Itamar Mushkin Sep 26 '19 at 06:06
  • Thanks, Itamar your solution works for me – A.D Sep 26 '19 at 06:10
  • Also suggest for the question posted at https://stackoverflow.com/questions/58112213/how-to-read-the-sublist-from-the-main-list-and-add-the-sublist-in-the-another-da – A.D Sep 26 '19 at 09:50

1 Answers1

0

There are various ways to do that.

One can create a function create_polygon that takes as input the dataframe (df), and the column name (columname). That would look like the following

def create_polygon(df, columnname):
    return {"__type":"Polygon", "coordinates":df[columnname]}

Considering that the column name will be Row_list, the following will already be enough

def create_polygon(df):
    return {"__type":"Polygon", "coordinates":df['Row_list']}

Then with pandas.DataFrame.apply one can apply it to the column Polypoints as follows

df['Polypoints'] = df.apply(create_polygon, axis=1)

As Itamar Mushkin mentions, one can also do it with a Lambda function as follows

df['Polypoints'] = df.apply(lambda row: {"__type":"Polygon", "coordinates":row['Row_list']} ,axis=1)
Gonçalo Peres
  • 11,752
  • 3
  • 54
  • 83