python - 将列重新排列到 Pandas 的下一行

标签 python python-3.x pandas

我有一个具有以下格式的数据框:-

ID   A    B    C     D     E     F
W1   a1   b1   c1    d1    e1    f1
W2   a2   b2   c2    d2    e2    f2
W3   a3   b3   c3    d3    e3    f3
W4   a4   b4   c4    d4    e4    f4
W5   a5   b5   c5    d5    e5    f5
W6   a6   b6   c6    d6    e6    f6

如果我想得到下面的格式。使用 Pandas 。

ID   A    B    E     F
W1   a1   b1   e1    f1
W1   c1   d1   e1    f1
W2   a2   b2   e2    f2
W2   c2   d2   e2    f2
W3   a3   b3   e3    f3
W3   c3   d3   e3    f3
W4   a4   b4   e4    f4
W4   c4   d4   e4    f4
W5   a5   b5   e5    f5
W5   c5   d5   e5    f5
W6   a6   b6   e6    f6
W6   c6   d6   e6    f6

然后将此数据帧分解为多个数据帧,以将第 1 列作为文件名写入单个 csv 文件。

W1.csv

W1   a1   b1   e1    f1
W1   c1   d1   e1    f1 

W2.csv

W2   a2   b2   e2    f2
W2   c2   d2   e2    f2

W3.csv

W3   a3   b3   e3    f3
W3   c3   d3   e3    f3

W4.csv

W4   a4   b4   e4    f4
W4   c4   d4   e4    f4

W5.csv

W5   a5   b5   e5    f5
W5   c5   d5   e5    f5

W6.csv

W6   a6   b6   e6    f6
W6   c6   d6   e6    f6

最佳答案

如果您已经确定C->AD->B,您可以重新连接帧然后填充。一般而言,d 只需要将您要移动的列与它们应放置在其下的列相关联。


d = dict(C='A', D='B')
u = df[[*d]].copy()
f = df.drop([*d], axis=1)

g = pd.concat([f, u.rename(columns=d)], sort=False).sort_index().ffill().groupby('ID')

现在您可以使用 g 将每个单独的帧写入您选择的文件:

for _, group in g:
    print(group, end='\n\n')

   ID   A   B   E   F
0  W1  a1  b1  e1  f1
0  W1  c1  d1  e1  f1

   ID   A   B   E   F
1  W2  a2  b2  e2  f2
1  W2  c2  d2  e2  f2

   ID   A   B   E   F
2  W3  a3  b3  e3  f3
2  W3  c3  d3  e3  f3

   ID   A   B   E   F
3  W4  a4  b4  e4  f4
3  W4  c4  d4  e4  f4

   ID   A   B   E   F
4  W5  a5  b5  e5  f5
4  W5  c5  d5  e5  f5

   ID   A   B   E   F
5  W6  a6  b6  e6  f6
5  W6  c6  d6  e6  f6

关于python - 将列重新排列到 Pandas 的下一行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55228531/

相关文章:

拆卸主窗口时 Python 崩溃

python - Popen.poll() 和 Popen.wait() 的区别

python - 在python中迭代两个不同大小的列表

python - Pandas Dataframes 到 MultiIndex Dataframe 的字典

python - 将表示时间戳列表的字符串转换为时间戳列表

python - 实际需要 global_variables_initializer() 时

python - VS Code Code Runner 不适用于 virtualenvs

python - 我怎样才能使它对大型项目列表更具可扩展性?

python - ValueError : Location based indexing can only have [integer, 整数切片,类似于整数, bool 数组]类型

python - 如何以我想要的格式获取我的 Python 日期?