python - 使用来自 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]
有任何想法吗?谢谢
解决方案
你可以试试:
mask = df['sentiment'].notnull()
df.loc[mask, 'sentiment'] = df.loc[mask, 'sentiment'].apply(lambda x: x['basic'])
推荐阅读
- c# - 发送 INotifyPropertyChanged 时窗口属性数据绑定未更新,但子元素属性是
- php - 如果没有选择新图像,则保留现有图像
- exception - 为什么 F# failwith 返回的是泛型类型而不是异常类型
- java - 如何正确设置 Selenium 测试
- angular - @Output 不从父组件触发方法
- node.js - 如何在异步函数中将对象推送到数组中
- google-cloud-platform - 我可以跟踪所有用户在 GCP 上的文件访问,即文件下载、读取等时间吗?
- android - strace 可以调试 gdb 正在调试的应用程序吗?
- macos - 在 Unity 中构建显示错误 Native error= Access denied
- github - 设置 GitHub 页面时出现权限被拒绝错误