将DataFrame从一行排列到多列中的Python代码。

huangapple go评论74阅读模式
英文:

Arranging the dataframe from one row to multiple columns in python

问题

以下是翻译好的部分:

我有一个包含单列但每行有多个值的数据帧。我需要正确地从每行中转置和附加数据。

数据帧如下所示:

    l1     l2
    0      a:1
           b:2
           c:3
    1      a:11
           b:12
           c:13
    2      a:21
           b:22
           c:33

列名 l1 是索引列,名为 l2 的列包含参数名称和值。我需要考虑 l2 列并安排数据帧为期望的输出。

期望的输出如下:

    a     b    c
    1     2    3
    11    12   13
    21    22   33

我尝试过的代码是转置数据帧:

df1 = df.T

但它应该将每行的值转置到列中。

英文:

I have a dataframe which contains single column but multiple values in the row . I need to transpose and append the data correctly from each row.

The dataframe is as follows:

l1     l2
0      a:1
       b:2
       c:3
1      a:11
       b:12
       c:13
2      a:21
       b:22
       c:33

The column name l1 is the index column and column named l2 contains the parameter name and value .I need to consider the l2 column and arrange the dataframe as the desired output.

The desired output is as follows:

a     b    c
1     2    3
11    12   13
21    22   33

The code which I have tried is of transposing .

df1=df.T

But It should Transpose each row value to the columns.

答案1

得分: 1

首先将索引l1转换为列,然后将空字符串替换为缺失值并进行向前填充,同时对l2列使用Series.str.split创建新的2列,最后使用DataFrame.pivot

df = df.reset_index()
df['l1'] = df['l1'].replace('', np.nan).ffill()
df[['l21', 'l22']] = df['l2'].str.split(':', expand=True)
print(df)
  l1    l2 l21 l22
0  0   a:1   a   1
1  0   b:2   b   2
2  0   c:3   c   3
3  1  a:11   a  11
4  1  b:12   b  12
5  1  c:13   c  13
6  2  a:21   a  21
7  2  b:22   b  22
8  2  c:33   c  33

df = df.pivot('l1', 'l21', 'l22')
print(df)
l21   a   b   c
l1             
0     1   2   3
1    11  12  13
2    21  22  33

希望这能帮助你进行代码部分的翻译。

英文:

First convert index l1 to column, then replace empty strings to missing values and forward filling them, also for column l2 is used Series.str.split to new 2 columns, last use DataFrame.pivot:

df = df.reset_index()
df['l1'] = df['l1'].replace('',np.nan).ffill()
df[['l21','l22']] = df['l2'].str.split(':', expand=True)
print (df)
  l1    l2 l21 l22
0  0   a:1   a   1
1  0   b:2   b   2
2  0   c:3   c   3
3  1  a:11   a  11
4  1  b:12   b  12
5  1  c:13   c  13
6  2  a:21   a  21
7  2  b:22   b  22
8  2  c:33   c  33

df = df.pivot('l1','l21','l22')
print (df)
l21   a   b   c
l1             
0     1   2   3
1    11  12  13
2    21  22  33

huangapple
  • 本文由 发表于 2020年1月6日 21:30:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613025.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定