Python数据表(或pandas):基于两列的数据框的棘手排序

输入数据


from datatable import dt


C1 = ['a', 'a', 'b', 'c']

C2 = ['b', 'c', 'a', 'a']


df1 = dt.Frame(C1=C1, C2=C2)

df1:


   | C1  C2

-- + --  --

 0 | a   b 

 1 | a   c 

 2 | b   a 

 3 | c   a 

输出数据


C1 = ['a', 'b', 'a', 'c']

C2 = ['b', 'a', 'c', 'a']


df2 = dt.Frame(C1=C1, C2=C2)

df2:


   | C1  C2

-- + --  --

 0 | a   b 

 1 | b   a 

 2 | a   c 

 3 | c   a 

将数据表对象转换为 pandas 对象:


df = df.to_pandas()

问题描述:


我尽力让它尽可能地易于理解。如果出现任何问题,我很乐意解释更多。示例数据在 C1 和 C2 列中包含唯一值“a”、“b”、“c”。C1 和C2 中的值的每个组合仅出现一次(例如,df1 的第一行中C1 = 'a' & C2 = 'b')。对于大多数组合,都有一个“对”,表示相反的组合(在本例中为上述示例:第三行中的 C1 = 'b' & C2 = 'a')。我如何订购这个数据框,使所有“对”都彼此相邻?所需的输出显示在 df2 中。我更喜欢使用数据表而不是熊猫。但如果有人在 pandas 中有解决方案,那对我同样有帮助。


看来我的样本数据过于简化。这是一个不太还原的数据集:


C1 = ['a', 'a', 'b', 'c']

C2 = ['b', 'c', 'a', 'a']

Values = [5, 10, 15, 20]


df1 = dt.Frame(C1=C1, C2=C2, Values=Values)


白板的微信
浏览 58回答 3
3回答

拉风的咖菲猫

这是您要找的吗:>>> from datatable import dt, f, sort, ifelse>>> df1 = dt.Frame(C1=['a', 'a', 'b', 'c'],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;C2=['b', 'c', 'a', 'a'],&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;Values=[5, 10, 15, 20])>>> df1[:, :, sort(ifelse(f.C1<f.C2, f.C1, f.C2),&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;ifelse(f.C1<f.C2, f.C2, f.C1))]&nbsp; &nbsp;| C1&nbsp; C2&nbsp; Values-- + --&nbsp; --&nbsp; ------&nbsp;0 | a&nbsp; &nbsp;b&nbsp; &nbsp; &nbsp; &nbsp; 5&nbsp;1 | b&nbsp; &nbsp;a&nbsp; &nbsp; &nbsp; &nbsp;15&nbsp;2 | a&nbsp; &nbsp;c&nbsp; &nbsp; &nbsp; &nbsp;10&nbsp;3 | c&nbsp; &nbsp;a&nbsp; &nbsp; &nbsp; &nbsp;20[4 rows x 3 columns]这里我们按 2 个计算列对框架进行排序,第一个是 C1 和 C2 中的最小值,第二个是 C1 和 C2 中的最大值。

繁花不似锦

尝试这个:import pandas as pdC1 = ['a', 'a', 'b', 'c']C2 = ['b', 'c', 'a', 'a']Values = [5, 10, 15, 20]df = pd.DataFrame({'C1': C1, 'C2': C2, 'Values': Values})srt = df.apply(lambda x: ','.join(sorted(x[['C1', 'C2']].values)),axis=1)df.loc[srt.argsort(),:]

汪汪一只猫

转换为 后pandas,我们可以sort_values尝试numpy.sortimport numpy as np&nbsp;df1 = df1.to_pandas()out = df1.iloc[pd.DataFrame(np.sort(df1.values,1)).sort_values([0,1]).index]Out[54]:&nbsp;&nbsp; C1 C20&nbsp; a&nbsp; b2&nbsp; b&nbsp; a1&nbsp; a&nbsp; c3&nbsp; c&nbsp; a
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python