熊猫转csv

时间:2018-08-16 12:28:31

标签: python pandas dataframe

我有以下熊猫系列:

0        [[1, 11283, 01, 5], [2,5, 1, 1]]
1        [[6, 33, 21, 2], [11283, 01, 5,1]] 
2        [[8430, 01, 2, 2],[2, 1, 1, 1]]

我需要将其另存为csv,但csv行应类似于以下内容:

1, 11283, 01, 5
2,5, 1, 1
6, 33, 21, 2
11283, 01, 5,1
8430, 01, 2, 2
2, 1, 1, 1

2 个答案:

答案 0 :(得分:4)

尝试:

df = pd.Series([[[1, 11283, 1, 5], [2,5, 1, 1]], 
                [[6, 33, 21, 2], [11283, 1, 5,1]], 
                [[8430, 1, 2, 2],[2, 1, 1, 1]]])

df.apply(pd.Series).stack().reset_index(drop=True)

与@ jezrael,@ coldspeed和许多其他熊猫神一样,建议在apply(pd.Series)中使用以下内容:

pd.DataFrame(df.values.tolist()).stack().reset_index(drop=True)

输出:

0    [1, 11283, 1, 5]
1        [2, 5, 1, 1]
2      [6, 33, 21, 2]
3    [11283, 1, 5, 1]
4     [8430, 1, 2, 2]
5        [2, 1, 1, 1]
dtype: object

答案 1 :(得分:1)

如果您不关心01成为1

df = pd.Series([[[1, 11283, 1, 5], [2,5, 1, 1]], 
                [[6, 33, 21, 2], [11283, 1, 5,1]], 
                [[8430, 1, 2, 2],[2, 1, 1, 1]]])
flat_list = [item for sublist in df.tolist() for item in sublist if item not in (',','[',']')]
pd.DataFrame(flat_list).to_csv('your_path')
相关问题