How To Split Columns In Pandas?
I have one question on how to split columns elements into many. If the dataframe looks like Src Dst A [A,B] B [B,A] C [C] D [D,E,F] E [E,D,F] F [F,D,E] ... this
Solution 1:
Check your column type with for both dataframe
df.Dst.apply(type)
#one of them should be str the 2nd one should be list
For the second one we just do explode
G = nx.from_pandas_edgelist(df.explode("Dst"), 'Src', 'Dst')
Solution 2:
I'm assuming you have only these 2 columns for your dataframe.
df["newcol1"]=[x[0] for x indf["Dst"]]
df["newcol2"]=[x[1] for x indf["Dst"]]
But if you want it to work for a Dataframe with X number of lists in each column, i believe the below code will help you out
split_df=df['Dst'].apply(lambda x: pd.Series(','.join(x).split(',')))
final_df=pd.concat([split_df,df],axis=1)
Post a Comment for "How To Split Columns In Pandas?"