将CSV中的数据重新整形为多列

时间:2018-01-10 03:33:16

标签: python pandas csv reshape

0   19   1   19   2   19  3   19

如何在python中将上面的csv数据更改为 -

0   19
1   19
2   19
3   19

现在我需要帮助重塑我看起来像这样的数据集 -

0   100   1   100   2   100  3   100  4   100  5   100     
6   200   7   200   8   200  9   200  0   200  1   200  
.....    

我想以下列格式重塑我的数据集 -

0 100
1 100
2 100
3 100
4 100
5 100
..
6 200
7 200
8 200
9 200
0 200
1 200
...

2 个答案:

答案 0 :(得分:2)

你真的不需要大熊猫。您可以使用np.loadtxt后跟reshape

来执行此操作
import io

# replace this with your filename 
buf = io.StringIO('''0   19   1   19   2   19  3   19''')   # buf = 'file.txt'

arr = np.loadtxt(buf).reshape(-1, 2)    
arr

array([[  0.,  19.],
       [  1.,  19.],
       [  2.,  19.],
       [  3.,  19.]])

请注意,如果您有不同的分隔符(例如逗号),则可以通过传递delimiter参数来指定它:np.loadtxt(buf, delimiter=',')

现在,使用savetxt -

保存为CSV
np.savetxt('file.csv', arr, delimiter=',')

稍后,使用pandas阅读CSV时,请使用 -

df = pd.read_csv(index_col=[0], header=None, names=['A', 'B'])

答案 1 :(得分:2)

from io import StringIO

txt = """0   19   1   19   2   19  3   19
"""

df = pd.read_csv(StringIO(txt),header=None,sep=' ')
df=df.dropna(1)

pd.DataFrame(df.T[0].values.reshape(df.shape[1]//2,2))
Out[77]: 
   0   1
0  0  19
1  1  19
2  2  19
3  3  19