我试图将一个宽的数据框[2行,12列]转换成一个长的数据框[4行,6列]。
From this ...
0 1 2 3 4 5 6 7 8 9 10 11
0 1.0 0.9 0.8 0.5 0.4 0.3 0.7 0.9 0.2 0.1 0.4 0.3
1 0.6 0.8 0.5 0.3 0.7 0.1 0.4 0.2 0.8 0.6 0.4 0.1
... to this ...
0 1 2 3 4 5
0 1.0 0.9 0.8 0.5 0.4 0.3
1 0.7 0.9 0.2 0.1 0.4 0.3
2 0.6 0.8 0.5 0.3 0.7 0.1
3 0.4 0.2 0.8 0.6 0.4 0.1
我的代码产生了意外的结果:
0 1 2 3 4 5 6 7 8 9 10 11
0 1.0 0.9 0.8 0.5 0.4 0.3
1 Nan Nan Nan Nan Nan Nan 0.7 0.9 0.2 0.1 0.4 0.3
etc...
我的代码:
import pandas as pd
import numpy as np
df = pd.DataFrame(
np.random.randn(2, 12)
)
slice_sz = 6
x = df.columns
col_num = len(x)
col_iter = int(col_num / slice_sz)
y = df.index
row_num = len(y)
df_list = pd.DataFrame([])
for row in range(row_num):
# print('Processing row', row)
i = 0
j = slice_sz - 1
for col in range(col_iter):
df_sliced = df.iloc[row, i:j]
df_sliced = df_sliced.to_frame()
df_sliced = df_sliced.transpose()
df_list = df_list.append(df_sliced)
df_sliced = []
i += slice_sz
j += slice_sz
我知道一定有更简洁的方法来完成这个问题。
感谢你的帮助。
df = pd.DataFrame(df.to_numpy().reshape(4,6))
它似乎对所有数据类型都有效。任务完成。 谢谢Ryno_XLI! - doing_the_best_I_can.reshape(-1,6)
和.reshape(4,-1)
与.reshape(4,6)
完全相同,因为原始形状是(2,12)。Reshape只是推断出“-1”值所需的行数,如果你给它一个6作为列数(对于(4,-1)的输入也是如此)。 - Ryno_XLI