当前位置: 动力学知识库 > 问答 > 编程问答 >

python - Pandas: Is there an idiomatic way to create rows for each value in a set of columns?

问题描述:

Is there an idiomatic way in pandas to create rows for each value in a set of columns in pandas like below?

import pandas as pd

mydf = pd.DataFrame({

'A': ['A1','A2','A3'],

'B': ['B1','B2','B3'],

'C': ['C1','C2','C3'],

'M1': [1,2,3],

'M2': [4,5,6]})

def reshape(dataframe, index_columns, index_colname):

attributes = [c for c in dataframe.columns if c not in index_columns]

dfs_out = []

for c in index_columns:

proj = [a for l in [[c], attributes] for a in l]

tdf = dataframe[proj]

proj[0] = index_colname

tdf.columns = proj

dfs_out.append(tdf)

return pd.concat(dfs_out, ignore_index=True)

print(reshape(mydf, ['A', 'B', 'C'], 'I'))

Outputs the following:

 I M1 M2

0 A1 1 4

1 A2 2 5

2 A3 3 6

3 B1 1 4

4 B2 2 5

5 B3 3 6

6 C1 1 4

7 C2 2 5

8 C3 3 6

网友答案:

You can also use pd.lreshape() to reshape wide-formatted data to a long one wherein it's groups keyword parameter accepts a dictionary, like groups ={new_name:columns_to_combine}

pd.lreshape(mydf, dict(I=list("ABC")))

网友答案:

Solution with melt, then need remove column variable:

print (pd.melt(mydf, id_vars=['M1','M2'], value_name='I').drop('variable', axis=1))
   M1  M2   I
0   1   4  A1
1   2   5  A2
2   3   6  A3
3   1   4  B1
4   2   5  B2
5   3   6  B3
6   1   4  C1
7   2   5  C2
8   3   6  C3
分享给朋友:
您可能感兴趣的文章:
随机阅读: