gpt4 book ai didi

python - 为我的数据框列获取唯一值作为新数据框的最快方法

转载 作者:太空宇宙 更新时间:2023-11-04 02:22:26 25 4
gpt4 key购买 nike

像这样转换数据的最佳方式是什么:

| 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

最佳答案

我认为您将不得不添加一个额外的索引,否则在每一列上,您只能添加一个行。

您可能正在寻找 DataFrame.unstack(..) .例如:

>>> 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

关于python - 为我的数据框列获取唯一值作为新数据框的最快方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51253712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com