python - 将 Pandas DataFrame 中的连续列转换为相应的行

标签 python pandas dataframe

尝试将 pandas 中的连续列转换为行。 例如:连续列名称是连续的数字以及一些字符串,即 Key1Val1 ,....,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'])

enter image description here

我尝试了 melt 函数,如下所示:

df.melt(id_vars=['City', 'State'], var_name='Column', value_name='Key')

但是我得到了以下输出:

enter image description here

问题是对于每个键,val 列都有不同的行。 预期输出如下:

enter image description here

最佳答案

使用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/

相关文章:

pandas - 就地适用于满足条件的 Pandas 数据框列

python - 通过 Pandas DataFrame 搜索子字符串的最有效方法是什么?

python - 如何将数据框中的值更改为值列表?

python - 将具有多个参数的函数应用于 pandas groupby 对象

python - Python 2.x 中的 nonlocal 关键字

python - 2个数据框之间的复杂链接

python - Pandas groupby + ifelse + 将新列添加回原始 df

r - 如何拆分数据框列并相应地复制行? [复制]

python - 对 3D 数组的行重新排序

python - 如何使用 tweepy 从带有地理标记的推文中获取位置?