简体   繁体   English

如何访问熊猫中的密钥

[英]How to access keys in pandas

How could i access keys in pandas, for example in the following dataframe my key is "d" , i'm trying to use print(df['d']['latitude']) but says key error, when i list the dataframe keys with df.keys() is only "d" , how can i access latitude and longitude?我如何访问 pandas 中的键,例如在以下数据框中,我的键是 "d" ,我正在尝试使用print(df['d']['latitude'])但是当我列出键错误时带有 df.keys() 的数据框键只有“d”,我如何访问纬度和经度?

Index(['_id', 'd'], dtype='object')
0             {'latitude': 35.685, 'longitude': 139.7514}
1                  {'latitude': 60.0, 'longitude': -95.0}
2       {'latitude': 54.94499999999999, 'longitude': -...
3       {'latitude': 41.32740000000001, 'longitude': -...
4       {'latitude': 42.83330000000001, 'longitude': 1...
                              ...
6000         {'latitude': 41.1412, 'longitude': -73.2637}
6001                {'latitude': 52.5, 'longitude': 5.75}
6002    {'latitude': 1.3667000000000087, 'longitude': ...
6003         {'latitude': 41.1412, 'longitude': -73.2637}
6004    {'latitude': 45.16669999999999, 'longitude': 2...
Name: d, Length: 6005, dtype: object

Thanks谢谢

If you want to access latitude (for example) for a specific index you may use如果您想访问特定索引的latitude (例如),您可以使用

df['d'].iloc[index]['latitude']

you should be able to iterate like so你应该能够像这样迭代

[x['latitude'] for x in df['d'].tolist()]

The best way is to load the json list items to dataframe .最好的方法是将json 列表项加载到dataframe A sample code is give below..下面给出了一个示例代码..

import json
from pandas import json_normalize

data = """
            {
            "coordinates":
                    [
                    {'latitude': 35.685, 'longitude': 139.7514},
                    {'latitude': 41.1412, 'longitude': -73.2637},
                    {'latitude': 60.0, 'longitude': -95.0},
                    {'latitude': 52.5, 'longitude': 5.75}
                    ],
            "status": ["ok"]
            }
        """
data_dict = json.loads(data)
df = json_normalize(data_dict["coordinates"])
df

Data Frame will be:数据框将是:

index指数 latitude纬度 longitude经度
0 0 35.685 35.685 139.7514 139.7514
1 1 41.1412 41.1412 -73.2637 -73.2637
2 2 60.0 60.0 -95.0 -95.0
3 3 52.5 52.5 5.75 5.75

if we print latitude only如果我们只打印纬度

df2["latitude"]
0 0 35.6850 35.6850
1 1 41.1412 41.1412
2 2 60.0000 60.0000
3 3 52.5000 52.5000

Name: latitude, dtype: float64名称:纬度,dtype:float64

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM