Skip to content Skip to sidebar Skip to footer

Reshaping Data In Csv To Multiple Columns

0 19 1 19 2 19 3 19 How can i change this above csv data in python to - 0 19 1 19 2 19 3 19 now i need help with reshaping my dataset which looks like this -

Solution 1:

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]: 
   010019111922193319

Solution 2:

You don't really need pandas. You can do this with np.loadtxt followed by a 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.]])

Note that if you have a different delimiter (example, comma), then you can specify it by passing a delimiter argument like so: np.loadtxt(buf, delimiter=',').

Now, save to CSV using savetxt -

np.savetxt('file.csv', arr, delimiter=',')

Later, when reading your CSV using pandas, use -

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

Post a Comment for "Reshaping Data In Csv To Multiple Columns"