简体   繁体   中英

Forming pandas dataframe from txt

Given a .txt file consisting of a long string of space-separated numbers

12 0 84 9 5 1 49 ......

I want to create a pandas dataframe such that the first 500 numbers form the first column, the next 500 numbers the 2nd column, etc. (in total 10000 columns).

How can this be implemented in python?

check out numpy.reshape . Example with 10 numbers

with open('xx.txt') as f:
    txt = f.read()

import pandas as pd
import numpy as np

txt_sep = np.array(txt.split())

txt_sep = txt_sep.reshape(5,-1)

df = pd.DataFrame(txt_sep)

output:

df
   0   1
0  1   2
1  3   4
2  5   6
3  7   8
4  9  10

In your case:

txt_sep = txt_sep.reshape(500,-1)

But this will only work if you have exactly 10000x500 numbers, but is fixable if this is your case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM