我正在尝试创建一个遍历 CSV 标头的字典列表。 对于每一列,我们需要检查空单元格并将字段更新为 True/False
我已经将 csv 加载到 pandas 数据框并创建了一个列列表。
输入CSV数据:
id | 姓名 | 位置 |
---|---|---|
1 | 亨利 | 伦敦 |
2 | 乔 | 秘鲁 |
3 | 南 | 德国 |
4 | 史密斯 | 南 |
输出:
[{项目:编号 is_null:假 序列:2} {项目名 is_null:真 序列:4} {项目位置 is_null:真 序列:6}]
需要帮助来迭代标题并获得输出。 我还在学习中,如果有任何错误,请指正我:)
你的问题不清楚,但我想你可能想要:
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}]
您可以为此使用列表理解:
[{"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
像下面这样的东西会起作用。
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}
]
首先,我相信你应该在问题中添加某种代码,这表明你尝试过。
现在至于你的查询, 你能做的是-
让我知道这是否有帮助,然后您可以通过发布一些尝试进行编辑,如果您仍然不明白,我们可以查看代码
编辑:我给出了一个简单的迭代方法,但是 mozway 回答的第一个解决方案绝对是最好的方法。