futui 发表于 2023-4-24 22:59:21

关于字典赋值的问题,求大师帮忙,谢谢

data =[["2345","A","2022-12-20","2.1016","-0.72","-0.77"],["004243","C","2022-12-15","2.0891","","-0.77"],
["519212","B","2022-12-10","","1.9733","-0.77","-3.29"],["162411","E","2022-12-9","0.7071","-1.64","-1.46"],
["007844","FC","2022-11-19","0.6967",None,"-1.46"],["163208","G","2022-11-10","1.0440","-0.40","-0.40"]]
columns = ["编号","名称","日期","AA","BB","C","数值88"]
df=pd.DataFrame(data,columns =columns)
#print(df)

dc = df.set_index("名称")["AA",'BB'].to_dict()
print(dc)

想建个字典
把名称列作为键名,AA列,BB列作为值,但我那个出错,求大师帮忙,谢谢

isdkz 发表于 2023-4-24 23:02:29

根据您的问题,我理解您想要基于名称列创建一个字典,并使用AA和BB列的值作为该名称的值。这里有一个修改过的解决方案:

import pandas as pd

data = [["2345", "A", "2022-12-20", "2.1016", "-0.72", "-0.77"],
      ["004243", "C", "2022-12-15", "2.0891", "", "-0.77"],
      ["519212", "B", "2022-12-10", "", "1.9733", "-0.77", "-3.29"],
      ["162411", "E", "2022-12-9", "0.7071", "-1.64", "-1.46"],
      ["007844", "FC", "2022-11-19", "0.6967", None, "-1.46"],
      ["163208", "G", "2022-11-10", "1.0440", "-0.40", "-0.40"]]
columns = ["编号", "名称", "日期", "AA", "BB", "C", "数值88"]
df = pd.DataFrame(data, columns=columns)

# 这里是主要的修改部分
dc = {name: {'AA': row['AA'], 'BB': row['BB']} for _, (name, row) in df.set_index('名称').iterrows()}
print(dc)


这将创建一个字典,其中名称作为键,AA和BB作为键值对的值。在这个示例中,您将得到以下结果:

{'A': {'AA': '2.1016', 'BB': '-0.72'},
'C': {'AA': '2.0891', 'BB': ''},
'B': {'AA': '', 'BB': '1.9733'},
'E': {'AA': '0.7071', 'BB': '-1.64'},
'FC': {'AA': '0.6967', 'BB': None},
'G': {'AA': '1.0440', 'BB': '-0.40'}}


请注意,这个字典在BB列中保留了空字符串和None值。根据您的需求,您可能需要在创建字典之前对这些值进行处理。

futui 发表于 2023-4-24 23:07:10

本帖最后由 futui 于 2023-4-24 23:09 编辑

大师,能做成这样的形式吗?
{'A': [ '2.1016', '-0.72'],
'C': ['2.0891', ''},.....


dc = {name: , row['BB']] for _, (name, row) in df.set_index('名称').iterrows()}
修改成这个样子,出错

isdkz 发表于 2023-4-24 23:17:20

futui 发表于 2023-4-24 23:07
大师,能做成这样的形式吗?
{'A': [ '2.1016', '-0.72'],
'C': ['2.0891', ''},.....


你应该使用`.iterrows()`遍历未设置索引的DataFrame。下面是正确的方法:

import pandas as pd

data = [["2345", "A", "2022-12-20", "2.1016", "-0.72", "-0.77"],
      ["004243", "C", "2022-12-15", "2.0891", "", "-0.77"],
      ["519212", "B", "2022-12-10", "", "1.9733", "-0.77", "-3.29"],
      ["162411", "E", "2022-12-9", "0.7071", "-1.64", "-1.46"],
      ["007844", "FC", "2022-11-19", "0.6967", None, "-1.46"],
      ["163208", "G", "2022-11-10", "1.0440", "-0.40", "-0.40"]]
columns = ["编号", "名称", "日期", "AA", "BB", "C", "数值88"]
df = pd.DataFrame(data, columns=columns)

# 这里是主要的修改部分
dc = {row['名称']: , row['BB']] for _, row in df.iterrows()}
print(dc)


这将创建一个字典,其中名称作为键,AA和BB作为键值对的值(作为一个列表)。在这个示例中,您将得到以下结果:

{'A': ['2.1016', '-0.72'],
'C': ['2.0891', ''],
'B': ['', '1.9733'],
'E': ['0.7071', '-1.64'],
'FC': ['0.6967', None],
'G': ['1.0440', '-0.40']}


这样,您将得到所需的字典格式。
页: [1]
查看完整版本: 关于字典赋值的问题,求大师帮忙,谢谢