将列的数据提取到变量中

时间:2019-08-07 00:22:06

标签: python pandas jupyter

我有一个非常大的数据框,其中的一列是字典本身。 (假设第12列)。在那本字典中,是我想得到的超链接的一部分。

在Jupyter中,我想显示一个表格,其中有第0列和第2列,以及完整的超链接

我认为我需要:

  • 从数据框中提取该字典
  • 从中获取特定的键值
  • 从提取的值中创建完整的超链接
  • 复制数据框并将列替换为上面创建的超链接

让我们解决第1步,接下来的步骤中我将提出其他问题。 如何将数据框中的值提取到可以使用的变量中?

import pytd
import pandas

client = pytd.Client(apikey=widget_api_key.value, database=widget_database.value)
results = client.query(query)
dataframe = pandas.DataFrame(**results)
dataframe
# Not sure what to do next

1 个答案:

答案 0 :(得分:0)

如果您只想从字典中提取一个键,并且该字典已作为字典存储在列中,则可以执行以下操作:

import numpy  as np
import pandas as pd

# assuming, your dicts are stored in column 'data'
# and you want to store the url in column 'url'
df['url']= df['data'].map(lambda d: d.get('url', np.NaN) if hasattr(d, 'get') else np.NaN)

# from there you can do your transformation on the url column

测试数据和结果

df= pd.DataFrame({
        'col1': [1, 5, 6],
        'data': [{'url': 'http://foo.org', 'comment': 'not interesting'}, {'comment': 'great site about beer receipes, but forgot the url'}, np.NaN],
        'json': ['{"url": "http://foo.org", "comment": "not interesting"}', '{"comment": "great site about beer receipes, but forgot the url"}', np.NaN]
    }
)

# Result of the logic above:
   col1                                               data             url
0     1  {'url': 'http://foo.org', 'comment': 'not inte...  http://foo.org
1     5  {'comment': 'great site about beer receipes, b...             NaN
2     6                                                NaN             NaN

如果需要测试,如果您的数据已经存储在python dict(而不是字符串)中,则可以按以下步骤进行操作:

print(df['data'].map(type))

如果将字典存储为字符串,则可以根据以下代码将其首先转换为字典:

import json

def get_url_from_json(document):
    if pd.isnull(document):
        url= np.NaN
    else:
        try:
            _dict= json.loads(document)
            url= _dict.get('url', np.NaN)
        except:
            url= np.NaN
    return url

df['url2']= df['json'].map(get_url_from_json)

# output:
print(df[['col1', 'url', 'url2']])   

   col1             url            url2
0     1  http://foo.org  http://foo.org
1     5             NaN             NaN
2     6             NaN             NaN