首页 > 解决方案 > 使用来自 json 数据集 Pandas 的行值在特定条件下更改行值

问题描述

我有这个数据集。

{
    "date": "2018-01-01", 
    "body": "some txt", 
    "id": 111, 
    "sentiment": null
}, 
{
    "date": "2018-01-02", 
    "body": "some txt", 
    "id": 112, 
    "sentiment": {
        "basic": "Bearish"
    }
}

我想用 pandas 来阅读这篇文章,并更改与 null 不同的每一行的列情绪。

当我这样做时:

pd.read_json(path)

这是我得到的结果:

body           ...    sentiment
0                      None
1                      {u'basic': u'Bullish'}

我不想拥有{u'basic': u'Bullish'}但只有基本的价值。所以要找到我使用的正确行

df.loc[self.df['sentiment'].isnull() != True, 'sentiment'] = (?)

它工作,但我不知道我必须放什么而不是(?)

我试过这个但没有用

df.loc[self.df['sentiment'].isnull() != True, 'sentiment'] = df['sentiment']['basic]

有任何想法吗?谢谢

标签: pythonpandasdataset

解决方案


你可以试试:

mask = df['sentiment'].notnull()
df.loc[mask, 'sentiment'] = df.loc[mask, 'sentiment'].apply(lambda x: x['basic'])

推荐阅读