首页 > 解决方案 > 如何在 Python 中将 DataFrame 列转换为行?

问题描述

我有以下数据集df_1,我想将其转换为df_2. 在df_2我已将 的列转换为(不包括和)中的df_1行。我查找了类似的答案,但他们提供的解决方案并不复杂。有没有一种简单的方法可以做到这一点?df_2UserIdDate

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

标签: pythonpython-3.xpandasdataframepandas-groupby

解决方案


您可以使用应用并连接所有行并对它们进行排序-

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

推荐阅读