Add a column from a Pandas dataframe to a new dataframe [Solved]

Question:

So I have a graph which I use to get the optimal path using Dijkstra. The path is returned as a list of index. I want to extract that path to a csv, but adding the coordinates to be able to visualize it using an external tool, to achieve this I iterate the path list and get the points from the original dataframe that have those index. I want to add these points to a new DataFrame to export this DF to a csv so I have a new csv for each path. How can I achieve this? I have this code but atm something is just now working because the "head" method throws this exception: ‘int’ object has no attribute ‘iloc’

The print(col) is working properly, so everything else is right, the issue must be when adding the row to the new DF.

df_out = pd.DataFrame
for node in path:
    row = df_cp.loc[df_cp["punto"] == node]
    print(row)
    df_out.add(row, other=True)

df_out.head(2)
df_out.to_csv('file_out2.csv', index=False)

I’ve tried uding join, add and append.

Asked By: Alberto

||

Answers:

I see 2 missing points in your code :

df_out = pd.DataFrame() –> missing parentheses at the end

Second, when adding a row to the DataFrame, right way is :

df_out = df_out.append(row)

Try this :

df_out = pd.DataFrame()
for node in path:
    row = df_cp.loc[df_cp["punto"] == node]
    df_out = df_out.append(row)

df_out.to_csv('file_out2.csv', index=False)
Answered By: everyt4u