迭代 CSV Header 并创建字典的 python 列表

问题描述 投票:0回答:4

我正在尝试创建一个遍历 CSV 标头的字典列表。 对于每一列,我们需要检查空单元格并将字段更新为 True/False

我已经将 csv 加载到 pandas 数据框并创建了一个列列表。

输入CSV数据:

id 姓名 位置
1 亨利 伦敦
2 秘鲁
3 德国
4 史密斯

输出:

  • item=列名
  • seq= i*2
  • is_null = 对于任何空单元格,否则为真 错

[{项目:编号 is_null:假 序列:2} {项目名 is_null:真 序列:4} {项目位置 is_null:真 序列:6}]

需要帮助来迭代标题并获得输出。 我还在学习中,如果有任何错误,请指正我:)

python python-3.x pandas opencv
4个回答
0
投票

你的问题不清楚,但我想你可能想要:

out = (
 df.isna().any()                # check if any NaN per col
   .rename_axis('item')         # set index name
   .reset_index(name='is_null') # set flag name
   .assign(seq=lambda x: range(2, 2*len(x)+2, 2)) # assign counter * 2
   .to_dict('records')          # convert to dictionary
)

或者,使用列表理解:

out = [{'item': col, 'is_null': df[col].isna().any(), 'seq': i*2}
       for i, col in enumerate(df, start=1)]

或:

out = [{'item': col, 'is_null': flag, 'seq': i*2}
       for i, (col, flag) in enumerate(df.isna().any().items(), start=1)]

输出:

[{'item': 'id', 'is_null': False, 'seq': 2},
 {'item': 'name', 'is_null': True, 'seq': 4},
 {'item': 'location', 'is_null': True, 'seq': 6}]

0
投票

您可以为此使用列表理解:

[{"item": c, "is_null": forms[c].isnull().values.any(), "seq": i * 2} for i, c in enumerate(df.columns, start=1)]

循环遍历每一列,为

item
键设置列名,检查该列中是否存在任何空值并将其设置为
is_null
,最后设置
seq


0
投票

像下面这样的东西会起作用。

import pandas as pd

# Dataframe
df = pd.DataFrame({'col1': [1, 2, 3, None, 5], 
                   'col2': ['a', 'b', 'c', None, 'e'], 
                   'col3': [True, False, True, True, None]})

# create a list of dictionaries with NaN value status and column index
null_list = [{'item': col, 'is_null': df[col].isnull().any(), 'seq': i*2} 
             for i, col in enumerate(df.columns)]

print(null_list)

输出:

[
 {'item': 'col1', 'is_null': True, 'seq': 0},
 {'item': 'col2', 'is_null': True, 'seq': 2},
 {'item': 'col3', 'is_null': True, 'seq': 4}
]

0
投票

首先,我相信你应该在问题中添加某种代码,这表明你尝试过。

现在至于你的查询, 你能做的是-

  1. 使用 df.columns 获取数据框中的列列表并将其转换为列表。
  2. 然后遍历此列表,您将获得项目键的值,seq 使用简单的东西,至于您的 is_null 只需执行 - df[col].isnull().values.any() [因此,如果任何values 为 null,这将返回 True else False]。

让我知道这是否有帮助,然后您可以通过发布一些尝试进行编辑,如果您仍然不明白,我们可以查看代码

编辑:我给出了一个简单的迭代方法,但是 mozway 回答的第一个解决方案绝对是最好的方法。

© www.soinside.com 2019 - 2024. All rights reserved.