将 CSV 中的数据重塑为多列
Reshaping data in CSV to multiple columns
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
...
你真的不需要 pandas。您可以使用 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'])
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
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
...
你真的不需要 pandas。您可以使用 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
-
np.savetxt('file.csv', arr, delimiter=',')
稍后,当使用 pandas
读取 CSV 时,请使用 -
df = pd.read_csv(index_col=[0], header=None, names=['A', 'B'])
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