像这样转换数据的最好方法是什么:
| col1 | col2 | ... col400
| tes | abc | max
| tes | onet | ups
如下所示:
Index | col | unique
1 | col1| tes
2 | col2| abc
3 | col2| onet
...
639 | col400| max
649 | col400| ups
发布于 2018-07-10 04:53:02
我认为您必须添加一个额外的索引,否则在每一列上,您只能添加一行。
您可能正在寻找。例如:
>>> df = pd.DataFrame([['tes', 'abc', 'max'], ['tes', 'onet', 'ups']], columns=["col1", "col2", "col400"])
>>> df
col1 col2 col400
0 tes abc max
1 tes onet ups
>>> df.unstack()
col1 0 tes
1 tes
col2 0 abc
1 onet
col400 0 max
1 ups
dtype: object
可能与.reset_index()
结合使用以引入具有唯一id和两列的索引:一列用于“原始行号”,另一列用于“列名”,如下所示:
>>> df.unstack().reset_index()
level_0 level_1 0
0 col1 0 tes
1 col1 1 tes
2 col2 0 abc
3 col2 1 onet
4 col400 0 max
5 col400 1 ups
或
df = (df.unstack()
.reset_index(level=0)
.rename(columns={'level_0':'col',0:'unique'})
.reset_index(drop=True))
df.index += 1
print(df)
# col unique
#1 col1 tes
#2 col1 tes
#3 col2 abc
#4 col2 onet
#5 col400 max
#6 col400 ups
https://stackoverflow.com/questions/51253712
复制相似问题