Python 反转数据帧并连接结果
我有一个两列的数据帧Python 反转数据帧并连接结果,python,pandas,dataframe,Python,Pandas,Dataframe,我有一个两列的数据帧 source | target ---------------- 1 3 2 4 2 1 这表示图形的边列表。目前,图表是有方向的。我想将其转换为无向图,因此我需要“互补”边,以便获得: source | target ---------------- 1 3 3 1 2 4 4 2 2 1 1 2 有没有任何方法可以直接在
source | target
----------------
1 3
2 4
2 1
这表示图形的边列表。目前,图表是有方向的。我想将其转换为无向图,因此我需要“互补”边,以便获得:
source | target
----------------
1 3
3 1
2 4
4 2
2 1
1 2
有没有任何方法可以直接在Pandas中执行此操作,而不使用图形库,如networkx
有没有什么方法可以直接在Pandas中执行此操作,而不使用图形库,例如networkx
我们可以使用df.iloc
反转df,然后使用df.append
out = df.append(pd.DataFrame(df.iloc[:,::-1].to_numpy(),index=df.index
,columns=df.columns)).sort_index().reset_index(drop=True)
或者使用np.flip
:
(df.append(pd.DataFrame(np.flip(df.to_numpy(),axis=1),
index=df.index,columns=df.columns)).sort_index().reset_index(drop=True))
注意:如果有更多的列,您可以将数据帧的子集作为
sub_df=df[['source','target']]]
并将df
替换为sub_df
i代码
@ShubhamSharma提出的另一个想法是使用set_axis
动态重命名列:
(df.append(df.iloc[:, ::-1].set_axis(df.columns, 1,inplace=False))
.sort_index().reset_index(drop=True))
有没有什么方法可以直接在Pandas中执行此操作,而不使用图形库,例如networkx
我们可以使用df.iloc
反转df,然后使用df.append
out = df.append(pd.DataFrame(df.iloc[:,::-1].to_numpy(),index=df.index
,columns=df.columns)).sort_index().reset_index(drop=True)
或者使用np.flip
:
(df.append(pd.DataFrame(np.flip(df.to_numpy(),axis=1),
index=df.index,columns=df.columns)).sort_index().reset_index(drop=True))
注意:如果有更多的列,您可以将数据帧的子集作为
sub_df=df[['source','target']]]
并将df
替换为sub_df
i代码
@ShubhamSharma提出的另一个想法是使用set_axis
动态重命名列:
(df.append(df.iloc[:, ::-1].set_axis(df.columns, 1,inplace=False))
.sort_index().reset_index(drop=True))
美丽的魔法,谢谢:)@Qubix很高兴我能帮忙:)干杯@anky是方法1
df.append(df.iloc[:,::-1).设置_轴(df.columns,1)).sort_index()
@ShubhamSharma很好的技巧,只需添加inplace=False
,以避免在较低版本的熊猫中出现警告:df.iloc[:,:-1].设置_轴(df.columns,1,inplace=False)).sort_index().reset_index().drop=True)
谢谢:-)美丽的魔法,谢谢:)@Qubix很高兴我能帮忙:)干杯@anky是方法1df.append(df.iloc[:,::-1).设置_轴(df.columns,1)).sort_index()
@ShubhamSharma很好的技巧,只需添加inplace=False
,以避免在较低版本的熊猫中出现警告:df.iloc[:,:-1].设置_轴(df.columns,1,inplace=False)).sort_index().reset_index().drop=True)
谢谢:-)