gpt4 book ai didi

Python - Pandas 数据框列交换

转载 作者:行者123 更新时间:2023-12-01 03:28:56 24 4
gpt4 key购买 nike

我有一个如下所示的数据框:

  |    A     |     B     |     C     |     D
0 | a | b | c | d | e | f | g | h
1 | a | b | c | d | e | f | NaN | NaN
2 | a | b | NaN | NaN | e | f | NaN | NaN
3 | a | b | NaN | NaN | NaN | NaN | NaN | NaN

我想把它改成这样:

    OBJ   VAL1   VAL2
0 A a b
1 A a b
2 A a b
3 A a b
4 A a b
5 A a b
6 B c d
7 B c d
8 C e f
9 C e f
10 C e f
11 D g h

因此多重索引也会转换为列。

请问有什么帮助吗?

是否有任何好的教程可以准确解释此类内容,以便我能够做到这一点,而不仅仅是尝试和错误?

谢谢

编辑:我的第一个原始数据框如下所示:

      A       B       C       D
0 (a,b) (c,d) (e,f) (g,h)
1 (a,b) (c,d) (e,f) NaN
2 (a,b) NaN (e,f) NaN
3 (a,b) NaN NaN NaN

所以每个单元格中都有一个元组。

最佳答案

您可以使用DataFrame.from_records首先,然后加倍reset_index如有必要sort_values用于对所有列进行排序:

df = pd.DataFrame({"A": [('a','b'),('a','b'),('a','b'),('a','b')], 
'B': [('c','d'),('c','d'), np.nan,np.nan],
'C':[('e','f'),('e','f'),('e','f'),np.nan],
'D':[('g','h'),np.nan,np.nan,np.nan]})
print (df)
A B C D
0 (a, b) (c, d) (e, f) (g, h)
1 (a, b) (c, d) (e, f) NaN
2 (a, b) NaN (e, f) NaN
3 (a, b) NaN NaN NaN

stacked = df.stack()
df1 = pd.DataFrame.from_records(stacked.tolist(), index = stacked.index)
.reset_index(level=0, drop=True)
.reset_index()
.sort_values(['index',0,1])
df1.columns = ['OBJ','VAL1','VAL2']
print (df1)
OBJ VAL1 VAL2
0 A a b
4 A a b
7 A a b
9 A a b
1 B c d
5 B c d
2 C e f
6 C e f
8 C e f
3 D g h
<小时/>

如果您的DataFrame在列中具有MultiIndex,则需要 stack第一:

stacked = df.stack()
df1 = pd.DataFrame.from_records(stacked.tolist(), index = stacked.index) \
.unstack(1) \
.swaplevel(0, 1, 1) \
.sort_index(axis=1) \
.replace({None:np.nan})

print (df1)
A B C D
0 1 0 1 0 1 0 1
0 a b c d e f g h
1 a b c d e f NaN NaN
2 a b NaN NaN e f NaN NaN
3 a b NaN NaN NaN NaN NaN NaN

df2 = df1.stack(0)
.reset_index(level=0, drop=True)
.reset_index()
.sort_values(['index',0,1])

df2.columns = ['OBJ','VAL1','VAL2']
print (df2)
OBJ VAL1 VAL2
0 A a b
4 A a b
7 A a b
9 A a b
1 B c d
5 B c d
2 C e f
6 C e f
8 C e f
3 D g h

关于Python - Pandas 数据框列交换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41157170/

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