Python 以最快的方式获取作为新数据帧的数据帧列的唯一值
以下哪种方式是转换数据的最佳方式:Python 以最快的方式获取作为新数据帧的数据帧列的唯一值,python,pandas,Python,Pandas,以下哪种方式是转换数据的最佳方式: | 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 我认为您必须添加一个额外的索引,否则在每一列上
| 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
我认为您必须添加一个额外的索引,否则在每一列上只能添加一行 你可能正在寻找。例如:
>>> 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 = (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
不应该包括
行
,因为否则只能有一个col1
,等等。不完全确定您的意思-请澄清一下好吗?数据框有一个索引(左边的项目)。但对于一个索引,只能有一行。这意味着只能有一个col400
,因为您只能在该值上映射一个值(例如max
)
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