【问题标题】:How to sort dataframe columns using for loop如何使用for循环对数据框列进行排序
【发布时间】:2018-08-23 01:03:16
【问题描述】:

我有一个 Python 数据框(名为 dfFull),它输出以下内容:

Email         System 6 System 7 System 1 System 4 Count System 5 System 3 System 2
test1@test.com  1         0         0        0       2     1         0       0
test2@test.com  0         1         0        1       3     0         1       0
test3@test.com  0         0         1        1       4     1         0       1

系统数量不同(系统数量在代码中较早计算,等于变量 SystemCount)。我想重组 Dataframe 以首先具有电子邮件和计数列,然后再按顺序排列所有系统。

我认为最好使用 for 循环并在下面设置循环,但我不确定要在循环中放入什么,因为我首先需要电子邮件和计数列(Python 新手)。我也知道 sort_values() 可能会起作用,但即使使用 python 文档,我也无法让参数正常工作

for count in range(1, int(SystemCount)+1): #counts up to the system amount

预期输出将是按此顺序排列的列及其内容:

Email Count System 1 ..... System 8

【问题讨论】:

  • 预期输出是什么?
  • 这个已经添加,谢谢

标签: python pandas sorting dataframe multiple-columns


【解决方案1】:

您可以通过来自difference 的所有列的第一列名称创建lambda key function

c = ['Email','Count']
c1 = df.columns.difference(c)
cols = c +  sorted(c1, key=lambda x: int(x.split()[1]))
print (cols)
['Email', 'Count', 'System 1', 'System 2', 'System 3', 
 'System 4', 'System 5', 'System 6', 'System 7']

df = df[cols]
print (df)
            Email  Count  System 1  System 2  System 3  System 4  System 5  \
0  test1@test.com      2         0         0         0         0         1   
1  test2@test.com      3         0         0         1         1         0   
2  test3@test.com      4         1         1         0         1         1   

   System 6  System 7  
0         1         0  
1         0         1  
2         0         0  

【讨论】:

  • 这很好,你能帮我理解这部分代码 sorted(c1, key=lambda x: int(x.split()[1]))
  • 您可以为自定义格式创建lambda key function - 这里按空格分割列的值,查看第二个值并转换为int,用于排序。
猜你喜欢
  • 2022-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-03
  • 2020-03-22
  • 2020-04-22
相关资源
最近更新 更多