python - 如何在 Python 中将 DataFrame 列转换为行?
问题描述
我有以下数据集df_1
,我想将其转换为df_2
. 在df_2
我已将 的列转换为(不包括和)中的df_1
行。我查找了类似的答案,但他们提供的解决方案并不复杂。有没有一种简单的方法可以做到这一点?df_2
UserId
Date
df_1
UserId Date -7 -6 -5 -4 -3 -2 -1 0 1 2 3 4 5 6 7
87 2011-05-10 18:38:55.030 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0
487 2011-11-29 14:46:12.080 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0
21 2012-03-02 14:35:06.867 0 1 0 1 2 0 2 2 0 1 2 2 1 3 1
df_2
day | count
-7 0
-7 0
-7 0
-6 0
-6 0
-6 1
-5 0
-5 1
-5 0
. .
. .(Similarly for other columns in between)
. .
6 0
6 0
6 3
7 0
7 0
7 1
解决方案
您可以使用应用并连接所有行并对它们进行排序-
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.random((3, 10)), columns=range(10))
df = df.T
new_df = pd.Series([], dtype=np.float64)
def f(x):
global new_df # not the most elegant way, something you could work upon?
new_df = pd.Series.append(new_df, x)
df.apply(f, axis=0)
new_df.sort_index(inplace=True)
print(new_df)
0 0.020673
0 0.710004
0 0.590984
1 0.643964
1 0.719694
1 0.105075
2 0.270417
2 0.537349
2 0.610228
3 0.391562
3 0.760375
3 0.105794
4 0.726044
4 0.676487
4 0.851921
5 0.447779
5 0.798975
5 0.877853
6 0.807380
6 0.639440
6 0.435890
7 0.263091
7 0.722340
7 0.586944
8 0.142973
8 0.928533
8 0.438123
9 0.076326
9 0.385373
9 0.662350
dtype: float64
推荐阅读
- bash - 使用 sshpass 在另一台服务器上运行命令
- delphi - 是否可以为 Delphi 创建一个通用调解器来处理通用命令
- drupal - 使用分类工具提示 drupal 7 悬停时分类描述不可见
- node.js - 当 lambda 从错误中退出时如何让 VSCode 终端不清除
- wireshark - 使用 tcprewrite 将 wifi 标头转换为 pcap 文件的以太网标头?
- javascript - HTML、CSS 和普通 JS 代码没有给出正确的输出
- javascript - 实时视频 Media Source Extensions API Error restarting video
- haskell - 如何将 MTL 风格、CPS 风格的高阶效果融入多义词中?
- javascript - 如何在附加逃生事件后重置自定义下拉菜单以显示菜单?
- python - 如何创建一个包含三个列表的数据框?