【问题标题】:Print Row and Column Header if column/row is not NaN Pandas如果列/行不是 NaN Pandas,则打印行和列标题
【发布时间】:2022-01-26 17:58:21
【问题描述】:

这是一个奇怪的问题 - 但如果数据框单元格不是 NaN,你们能想出一个好方法来打印行或行列表及其对应的列标题吗?

想象一个这样的数据框:

     col1   col2    col3    col4
1    1      NaN     2       NaN
2    NaN    NaN     1       2
3    2      NaN     NaN     1

结果应该是这样的:

1    [col1: 1, col3: 2]
2    [col3: 1, col4: 2]
3    [col1: 2, col4: 1]

提前致谢!

【问题讨论】:

标签: python pandas


【解决方案1】:

您可以转置数据帧,并为每一行删除 NaN 并转换为 dict:

out = df.T.apply(lambda x: dict(x.dropna().astype(int)))

输出:

>>> out
1    {'col1': 1, 'col3': 2}
2    {'col3': 1, 'col4': 2}
3    {'col1': 2, 'col4': 1}
dtype: object

【讨论】:

  • 转置计算成本很高。如果您必须在数据帧级别处理它,请使用堆栈
【解决方案2】:

让我们试试stack

df.stack().reset_index(level=0).groupby('level_0')[0].agg(dict)
Out[184]: 
level_0
1    {'col1': 1.0, 'col3': 2.0}
2    {'col3': 1.0, 'col4': 2.0}
3    {'col1': 2.0, 'col4': 1.0}
Name: 0, dtype: object

【讨论】:

    【解决方案3】:

    结合 agg(dict) 和列表理解

    d = [{k:v for k, v in x.items() if v == v } for x in df.agg(dict,1)]
    
    [{'col1': 1.0, 'col3': 2.0},
     {'col3': 1.0, 'col4': 2.0},
     {'col1': 2.0, 'col4': 1.0}]
    

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 1970-01-01
      • 2014-08-12
      • 1970-01-01
      • 2016-12-31
      • 2020-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多