如何解决将循环中的打印语句输出转换为数据帧
我正在尝试将以下代码从打印语句调整为数据帧输出。
places = ['England UK','Paris FRANCE','ITALY,gh ROME','New']
location=['UK','FRANCE','ITALY']
def on_occurence(pos,location):
print (i,':',location)
root = aho_create_statemachine(location)
for i in places:
aho_find_all(i,root,on_occurence)
以上代码的打印输出为
英国英国:英国
法国巴黎:法国
意大利,gh 罗马:意大利
我希望 df 看起来像这样:
留言 | 国家 |
---|---|
英国英国 | 英国 |
法国巴黎 | 法国 |
意大利,gh罗马 | 意大利 |
我尝试了以下但没有运气
places = ['England UK','ITALY']
df = pd.DataFrame(columns=["message","location"])
def on_occurence(pos,location)
df = df.append({"message":i,"location":location},ignore_index=True)
root = aho_create_statemachine(location)
for i in places:
aho_find_all(i,on_occurence)
但是 df 如下所示
留言 | 国家 |
---|---|
新 | 英国 法国 意大利 |
解决方法
我建议使用字典而不是 2 个单独的列表 EG:
placeAndLocation = {
"england UK" : "UK","Paris France" : "france"
}
等等然后循环使用这个用法
for place,location in placeAndLocation.items():
print("place: " + place)
print("location: " + location)
我发现这更容易,因为您可以轻松查看哪些数据字段与哪些值对齐,并且数据包含在一个变量中,从而更容易重新记录该行
, df = pd.DataFrame(list(zip(places,location)),columns = ["Message","Country"])
print(df)
我的输出:
Message Country
0 England UK UK
1 Paris FRANCE FRANCE
2 ITALY,gh ROME ITALY
如果你想在没有行索引的情况下打印它:
print(df.to_string(index=False))
这种情况下的输出是:
Message Country
England UK UK
Paris FRANCE FRANCE
ITALY,gh ROME ITALY
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。