英文:
Add a column from a Pandas dataframe to a new dataframe
问题
这是你要翻译的部分:
我有一个图表,我使用Dijkstra算法获取最佳路径。路径作为索引列表返回。我想提取该路径到CSV文件,但要添加坐标以便使用外部工具进行可视化。为了实现这一目标,我遍历路径列表并从原始数据框中获取具有这些索引的点。我想将这些点添加到一个新的数据框中,以便导出该数据框到CSV文件,以便每个路径都有一个新的CSV文件。我该如何实现这一目标?我有以下代码,但目前某些地方出现问题,因为"head"方法引发此异常:"int"对象没有"iloc"属性。
print(col)正常工作,所以其他一切都没问题,问题可能出现在将行添加到新数据框时。
请注意,我已将代码部分略过,只提供了文本翻译。
英文:
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.
答案1
得分: 1
df_out = pd.DataFrame()
--> 代码中缺少末尾的括号
当向DataFrame添加行时,正确的方式是:
df_out = df_out.append(row)
尝试这样做:
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)
英文:
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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论