|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
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列作为值,但我那个出错,求大师帮忙,谢谢
你应该使用`.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['AA'], 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']}
这样,您将得到所需的字典格式。
|
|