我有一些像
这样的数据moved_to_matrix [[0, 1, 0]]
companies [Barcelona, Madrid, Amsterdam]
moved_from_matrix [[0, 0, 1]]
我想弄清楚如何将它转换为Pandas / Numpy中的转换矩阵。有没有人有任何想法。我试过pd.melt,但它对我来说没有用。
答案 0 :(得分:1)
您可以使用:
df = pd.DataFrame({'a':['moved_to_matrix','companies','moved_from_matrix'],
'b':[[[0, 1, 0]], ['Barcelona', 'Madrid', 'Amsterdam'], [[0, 0, 1]]]})
print (df)
a b
0 moved_to_matrix [[0, 1, 0]]
1 companies [Barcelona, Madrid, Amsterdam]
2 moved_from_matrix [[0, 0, 1]]
#remove nested list
df.b = df.b.mask(df.b.str.len() == 1, df.b.str[0])
print (df)
a b
0 moved_to_matrix [0, 1, 0]
1 companies [Barcelona, Madrid, Amsterdam]
2 moved_from_matrix [0, 0, 1]
#create columns by df constructor
df = pd.DataFrame(df.b.values.tolist(), index=df.a).reset_index()
df.columns = ['a','b','c','d']
print (df)
a b c d
0 moved_to_matrix 0 1 0
1 companies Barcelona Madrid Amsterdam
2 moved_from_matrix 0 0 1