pandot数据帧中的列和列值

时间:2017-07-10 13:53:06

标签: python pandas dictionary dataframe

我的数据框看起来像这样,但有26行和110列:

index/io   1   2   3   4
  0        42  53  23  4
  1        53  24  6   12
  2        63  12  65  34
  3        13  64  23  43

期望的输出:

index  io  value
0      1   42
0      2   53
0      3   23
0      4   4
1      1   53
1      2   24
1      3   6
1      4   12
2      1   63
2      2   12
... 

我尝试使用dict和list将数据帧转换为dict,然后使用索引值创建一个新列表,并使用io更新新的dict。

indx = []

for key, value in mydict.iteritems():
    for k, v in value.iteritems():
        indx.append(key)
indxio = {}
for element in indx:
    for key, value in mydict.iteritems():
        for k, v in value.iteritems():
            indxio.update({element:k})

我知道这可能太过分了,但这是我唯一能想到的。这个过程太长了,所以我停了下来。

2 个答案:

答案 0 :(得分:4)

您可以使用set_indexstackreset_index()

df.set_index("index/io").stack().reset_index(name="value")\
  .rename(columns={'index/io':'index','level_1':'io'})

输出:

    index io  value
0       0  1     42
1       0  2     53
2       0  3     23
3       0  4      4
4       1  1     53
5       1  2     24
6       1  3      6
7       1  4     12
8       2  1     63
9       2  2     12
10      2  3     65
11      2  4     34
12      3  1     13
13      3  2     64
14      3  3     23
15      3  4     43

答案 1 :(得分:4)

您需要set_index + stack + rename_axis + reset_index

df = df.set_index('index/io').stack().rename_axis(('index','io')).reset_index(name='value')
print (df)
    index io  value
0       0  1     42
1       0  2     53
2       0  3     23
3       0  4      4
4       1  1     53
5       1  2     24
6       1  3      6
7       1  4     12
8       2  1     63
9       2  2     12
10      2  3     65
11      2  4     34
12      3  1     13
13      3  2     64
14      3  3     23
15      3  4     43

使用meltrename的解决方案,但是值的顺序不同,因此需要sort_values

d = {'index/io':'index'}
df = df.melt('index/io', var_name='io', value_name='value') \
       .rename(columns=d).sort_values(['index','io']).reset_index(drop=True)
print (df)
    index io  value
0       0  1     42
1       0  2     53
2       0  3     23
3       0  4      4
4       1  1     53
5       1  2     24
6       1  3      6
7       1  4     12
8       2  1     63
9       2  2     12
10      2  3     65
11      2  4     34
12      3  1     13
13      3  2     64
14      3  3     23
15      3  4     43

为numpy爱好者提供替代解决方案:

df = df.set_index('index/io')
a = np.repeat(df.index,  len(df.columns))
b = np.tile(df.columns, len(df.index))
c = df.values.ravel()
cols = ['index','io','value']
df = pd.DataFrame(np.column_stack([a,b,c]), columns = cols)
print (df)
   index io value
0      0  1    42
1      0  2    53
2      0  3    23
3      0  4     4
4      1  1    53
5      1  2    24
6      1  3     6
7      1  4    12
8      2  1    63
9      2  2    12
10     2  3    65
11     2  4    34
12     3  1    13
13     3  2    64
14     3  3    23
15     3  4    43