python中的行操作

2024-09-21 11:37:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试将csv转换成一个.gexf格式的文件,用于动态gephi图形。其思想是在属性数据中包含所有的平行边(具有相同源和目标但后期日期不同的边)。在本例中,属性中的所有日期都与John在在线课程讨论区回答Jan问题的发布日期相对应。在

我怎样才能得到这样的csv:

Jan John    2012-04-07  2012-06-06
Jan Jason   2012-05-07  2012-06-06
Jan John    2012-03-02  2012-06-07
Jan Jason   2012-03-20  2012-06-08
Jan Jack    2012-03-26  2012-06-09
Jan Janet   2012-05-01  2012-06-10
Jan Jack    2012-05-04  2012-06-11
Jan Jason   2012-05-07  2012-06-12
Jan Jack    2012-05-09  2012-06-13
Jan John    2012-05-15  2012-06-14
Jan Janet   2012-05-15  2012-06-15
Jan Jason   2012-05-20  2012-06-16
Jan Jack    2012-05-23  2012-06-17
Jan Josh    2012-05-25  2012-06-18
Jan Jack    2012-05-28  2012-06-19
Jan Josh    2012-06-01  2012-06-20

格式如下:

^{pr2}$

我尝试的方法效果不太好。我尝试创建两个列表,对于第一个列表中的每个条目,搜索第二个列表中前两个条目的匹配。如果有匹配项,那么我的脚本将删除第二个列表中的行并附加日期对。当每一行代表提问者和回答者之间的完全对应数量时,我将编写一个脚本将该行转换为边缘/属性数据。我一直在使用this as some sort of guide。在


Tags: 文件csv脚本列表格式动态johnjan
1条回答
网友
1楼 · 发布于 2024-09-21 11:37:39

看看Python pandas项目,它旨在简化这种操作。一个它如何分组和解析你的数据的例子。。。。在

# Load your CSV as a pandas 'DataFrame'.
In [13]: df = pd.read_csv('your file', names=['source', 'target', 'start', 'end'])

# Look at the first few rows. It worked.
In [14]: df.head()
Out[14]: 
  source target       start         end
0    Jan  Jason  2012-05-07  2012-06-06
1    Jan   John  2012-03-02  2012-06-07
2    Jan  Jason  2012-03-20  2012-06-08
3    Jan   Jack  2012-03-26  2012-06-09
4    Jan  Janet  2012-05-01  2012-06-10

# Group the rows by the the name columns. Each unique pair gets its own group.
In [15]: edges = df.groupby(['source', 'target'])

In [16]: for (source, target), edge in edges: # consider each unique name pair an edge
    print source, target
    for _, row in edge.iterrows(): # loop through all the rows belonging to these names
        print row['start'], row['end']
   ....:         
Jan Jack
2012-03-26 2012-06-09
2012-05-04 2012-06-11
2012-05-09 2012-06-13
2012-05-23 2012-06-17
2012-05-28 2012-06-19
Jan Janet
2012-05-01 2012-06-10
2012-05-15 2012-06-15
Jan Jason
2012-05-07 2012-06-06
2012-03-20 2012-06-08
2012-05-07 2012-06-12
2012-05-20 2012-06-16
Jan John
2012-03-02 2012-06-07
2012-05-15 2012-06-14
Jan Josh
2012-05-25 2012-06-18
2012-06-01 2012-06-20

剩下的就是用XML详细说明这些print语句,并可能输出到一个文件而不是打印。在

相关问题 更多 >

    热门问题