【问题标题】:Making seperate columns from dictionary items in the same df in Python在Python中的相同df中从字典项中创建单独的列
【发布时间】:2021-05-10 21:55:36
【问题描述】:

我有一个巨大的 twitter 数据数据框 (9530232x19)。第一列包括一个字典。我想在同一个 df 中从该字典项中创建单独的列。此外,我在“实体”列中有一本字典,我想进行类似的分隔。 我想将指标添加为四个新列,例如“rtcount”、“reply_count”、“like_count”和“quote_count”,并将实体[“htype”]作为我现有df右侧的新列,而不创建更多数据帧,因为这个大 df 几乎使用了我所有的 16 GB RAM,并且偶尔会崩溃。我知道对这个大 df 使用 for 循环不是一种有效的方法,但我不知道该怎么做。
非常感谢任何帮助。

htypedf=[]
t=[]
for i in range(0,len(d)):
    if i%100==0:
        print(i)
    htype=[]
    hasht=[]
    t=d[i:i+1]
    metrics=pd.Series(t['public_metrics'][0]).to_frame().T
    try:
        htype=list(map(lambda x : x['type'], t['entities'][0]['annotations']))
    except:
        htype=('NaN')

    d.iloc[i] = pd.concat([t, metrics, pd.DataFrame({'htype': [htype]})],axis=1)

【问题讨论】:

    标签: python pandas dictionary add


    【解决方案1】:

    试试这个,而不是你的 for 循环:

    d = pd.concat([t.drop['public_metrics'], t['public_metrics'].apply(pd.Series)], axis=1)
    

    类似的概念可以应用于获取 htype,但处理方式将取决于您希望如何保留数据。如果您想要实体列中的 htype,您可能会试一试:

    d = pd.concat([t.drop['entities'], t['entities'].apply(pd.Series)['htype']], axis=1)
    

    要在新的 htype 列之外保留实体列,您应该能够改用以下代码(只需删除 drop 函数):

    d = pd.concat([t, t['entities'].apply(pd.Series)['htype']], axis=1)
    

    让我知道这对你有什么作用!

    新代码块:

    def fetch_htype(row):
        entities_dict = row['entities']
        if np.isnan(entities_dict):
            return pd.Series(data = '', index = ['htype'])
        else:
            return pd.Series(data = entities_dict['htype'], index = ['htype'])
    
    d = pd.concat([d, t.apply(fetch_htype)], axis=1)
    

    【讨论】:

    • 非常感谢,第一个报错了,但是我删除了t.drop['entities']部分,为public_metrics工作。现在问题出在第二个。一些“实体”是 NaN,因此它说“TypeError:'float' object is not subscriptable”。这行代码如何忽略 Nans?
    • 如下再试第一部分。如果可行,我将编辑我的回复! d = pd.concat([t, t['public_metrics'].apply(pd.Series)], axis=1)
    • 完美运行!而且非常非常快。谢谢!第二个有机会吗?
    • 哦,对不起;我误解了!对于具有 NaN 并抛出错误的实体,有两种选择:1)更改传递给 apply 的函数以考虑 NaN,或 2)在应用之前处理 NaN。 2 可能更容易,所以我正在编辑我的帖子以说明这一点。试试底部代码块中的新代码!
    • 它不起作用,没有对数据进行任何修改。 NaN 仍然存在。我之前尝试过一次,结果是一样的。无法更改该列。
    猜你喜欢
    • 1970-01-01
    • 2017-10-09
    • 2017-05-05
    • 1970-01-01
    • 2014-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-06-25
    • 1970-01-01
    相关资源
    最近更新 更多