我的数据帧太长,我想把它包装到下一列中。这种方法可行,但我相信还有更好的方法。我想要一个答案,甚至更长的数据帧,包装线1模3。你知道吗
import pandas as pd
import numpy as np
def wraparound(df, row_number):
"""row_number is the first number that we wrap onto the next column."""
n = row_number - 1
r = df.iloc[:n]
r = pd.concat([r, df.iloc[n:2*n].reset_index(drop=True)], axis=1)
r = pd.concat([r, df.iloc[2 * n:3*n].reset_index(drop=True)], axis=1)
r = r.reset_index(drop=True).T.reset_index(drop=True).T
return r
df = pd.DataFrame.from_records([
(1, 11),
(2, 12),
(3, 13),
(4, 14),
(5, 15),
(6, 16),
(7, 17),
])
result = wraparound(df, 4)
expected = pd.DataFrame.from_records([
(1, 11, 4, 14, 7, 17),
(2, 12, 5, 15, np.nan, np.nan),
(3, 13, 6, 16, np.nan, np.nan),
])
pd.testing.assert_frame_equal(result, expected)
您可以先创建} 创建^{} :
MultiIndex
,然后使用^{相关问题 更多 >
编程相关推荐