尝试将 pandas 中的连续列转换为行。 例如:连续列名称是连续的数字以及一些字符串,即 Key1
、Val1
,....,DataFrame
中的KeyN
,ValN
。您可以使用下面的代码来生成数据框。
df = pd.DataFrame({'City': ['Houston', 'Austin', 'Hoover'],'State': ['Texas', 'Texas', 'Alabama'],'Name':['Aria', 'Penelope', 'Niko'],'Key1':["test1", "test2", "test3"],'Val1':[28, 4, 7],'Key2':["test4", "test5", "test6"],
'Val2':[82, 45, 76],'Key3':["test7", "test8", "test9"],'Val3':[4, 76, 9],'Key4':["test10", "test11", "test12"],'Val4':[97, 66, 10],'Key5':["test13", "test14", "test15"],'Val5':[4, 10, '']},columns=['City', 'State', 'Name', 'Key1', 'Val1', 'Key2', 'Val2', 'Key3', 'Val3', 'Key4', 'Val4', 'Key5', 'Val5'])
我尝试了 melt
函数,如下所示:
df.melt(id_vars=['City', 'State'], var_name='Column', value_name='Key')
但是我得到了以下输出:
问题是对于每个键,val 列都有不同的行。 预期输出如下:
最佳答案
使用pd.wide_to_long
:
pd.wide_to_long(df,['Key', 'Val'],['City', 'State', 'Name'],'No').reset_index()
输出:
City State Name No Key Val
0 Houston Texas Aria 1 test1 28
1 Houston Texas Aria 2 test4 82
2 Houston Texas Aria 3 test7 4
3 Houston Texas Aria 4 test10 97
4 Houston Texas Aria 5 test13 4
5 Austin Texas Penelope 1 test2 4
6 Austin Texas Penelope 2 test5 45
7 Austin Texas Penelope 3 test8 76
8 Austin Texas Penelope 4 test11 66
9 Austin Texas Penelope 5 test14 10
10 Hoover Alabama Niko 1 test3 7
11 Hoover Alabama Niko 2 test6 76
12 Hoover Alabama Niko 3 test9 9
13 Hoover Alabama Niko 4 test12 10
14 Hoover Alabama Niko 5 test15
您正在尝试同时熔化两根柱子。 pd.wide_to_long 处理这种情况。
关于python - 将 Pandas DataFrame 中的连续列转换为相应的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68214806/