示例输入数据帧:
merged_df
Full Name Kommata 2007 Kommata 2015 Kommata 2019
0 Athanasios bouras New democracy New democracy New democracy
1 Andreas loverdos Pasok Pasok-democratic alignment Movement for change
2 Theodora tzakri Pasok Pasok Syriza
3 Thanasis zempilis Pasok NaN New democracy
所需数据帧:
edges_df
Source Target
0 New democracy_2007 New democracy_2015
1 New democracy_2015 New democracy_2019
2 Pasok_2007 Pasok-democratic alignment_2015
3 Pasok-democratic alignment_2015 Movement for change_2019
4 Pasok_2007 Pasok_2015
5 Pasok_2015 Syriza_2019
6 Pasok_2007 New democracy_2019
如上所述,我有一个包含n列的输入数据帧;第一个数据帧有唯一的值(Full Name
),另一个n-1(Kommata YYYY
)是行的一些属性。我想生成一个包含两列的新数据帧,如下所示:
对于每个Full Name
,它将有0行或更多行
从最左边的Kommata
列开始,它接受每个相邻的非空值对,例如Kommata 2007-Kommata 2015, Kommata 2015-Kommata 2019
;只有当Kommata 2015
为空时,对Kommata 2007-Kommata 2019
才能存在
每对都将是一个新行
每列的值修改如下:value\u YYYY,其中值保持不变,YYYY取自列名(例如'{}_{}'.format(prev_value, col_name.split()[-1])
)
提前谢谢
可以使用
pd.melt
执行以下操作:我假设输出的顺序无关紧要。此代码的输出将按“全名”的字母顺序排序。
如果需要保持顺序,则需要修改
df.sort_values
行,以便按照“全名”的原始顺序排序,而不是按字母顺序排序。你知道吗相关问题 更多 >
编程相关推荐