【问题标题】:Traversing a dictionary in a python Dataframe在 python Dataframe 中遍历字典
【发布时间】:2020-10-30 07:57:39
【问题描述】:

我正在尝试遍历我的 python Dataframe 行中存在的字典。请参阅下面的 Dataframe 的一行以供参考: 状态栏为空。

未命名:0 城市州国家邮政编码距离
720 4976 巴塞罗那西班牙 08001 {'08001': 0, '08002': 2.2, '08003': 2.2}

当我运行以下代码时,会出现此错误-> TypeError: string indices must be integers

代码:

import sys
import json
import pandas as pd
dfglobal=pd.read_csv("postcoderadius.csv")
#print(dfglobal)
filtered_df2  = pd.DataFrame([])
# s=sys.argv[1]
# ci=s[s.find("City=")+5:s.find("&State")]
# cs=s[s.find('State')+6:s.find("&Country")]
# ci=ci.replace('+','')
# cs=cs.replace('+','-')
# co=s[s.find("Country")+8:s.find("&ZipCode")]
# givenpostal=s[s.find("ZipCode")+8:s.find("&Radius")]
# radius=float(s[s.find("Radius")+8:])
ci="Barcelona"
co="Spain"
cs=""
givenpostal="08001"
radius=4.0
print(ci,co,cs,givenpostal,radius)
#print("hello1")
filtered_df2=pd.concat([filtered_df2,dfglobal[(dfglobal['Country'] == co) & (dfglobal['City'] == ci) &  (dfglobal['PostalCode'] == givenpostal)]])
#print(filtered_df2)
#filtered_df2['PostalCode']=filtered_df2['PostalCode'].apply(str)
a_dict=filtered_df2['Distance']
#print(a_dict)
result  = pd.DataFrame([])
resp=[]
resr=[]
for index, row in filtered_df2.iterrows():
    #print(row['Distance'])
    dictp=row['Distance']
    for key in dictp: 
        print(dictp[key])


result['PostalCode']=resp
result['City']=ci
result['Country']=co
result['Radius']=resr
result=result.reindex(["City","Country","PostalCode","Radius"],axis=1)
result.to_csv("distance.csv")    

【问题讨论】:

  • 您能否发布更多示例数据,以便我进行一些测试并进一步调查?另外,Unnamed 是一列吗?
  • 是 unnamed:0 是一列

标签: python python-3.x pandas dictionary


【解决方案1】:

看起来row['Distance'] 没有返回字典, 而是一个字符串。 (如果没有,请给出一个完整的、可重现的例子)

所以dictp = row['Distance']之后dictp是一个字符串。

for key in dictp 将返回字符串的每个字母。

print(dictp[key]) 然后会导致错误,因为对于字符串, key 需要是一个数字。

您可以通过在dictp=row['Distance'] 行之后打印type(dictp) 来检查这是否是您的问题。如果这打印出str,那就是原因。

以下是解决此问题的方法:

您可以使用eval()函数将字符串转换为真正的字典。

像这样:

dictp = "{'08001': 0, '08002': 2.2, '08003': 2.2}"
mydict = eval(dictp)

请注意,如果您不能保证所有行都确实有一个字典,那么这是一个安全风险,因为它运行代码。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-29
    • 2023-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-09-22
    相关资源
    最近更新 更多