将Pandas数据框中的一列添加到新数据框中。

huangapple go评论71阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2023年3月15日 17:51:50
  • 转载请务必保留本文链接:https://go.coder-hub.com/75743024.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定