python - 切片包含 dic 值的 Pandas 列
问题描述
下面是我的DF:
df = pd.DataFrame({'Name': ['AZ', 'AF'], 'Other_Name': [np.nan, [{'name': 'ARES ZAN', 'language': 'en', 'type': 'ALTERNATIVE'}]]})
Name Other_Name
0 AZ NaN
1 AF [{'name': 'ARES ZAN', 'language': 'en', 'type': 'ALTERNATIVE'}]
目的是用“Other_Name_name”、“Other_Name_language”、“Other_Name_type”替换“Other_Name”列
我遵循了以下帮助:Slice pandas dataframe json column into columns
此外,由于我有一些 NaN(我不想删除),因此该解决方案不起作用。
感谢任何人的帮助!
解决方案
def change_key(x):
for data_dict in x:
for key in list(data_dict.keys()):
data_dict[f'Other_Name_{key}'] = data_dict.pop(key)
return x
df.loc[~df['Other_Name'].isnull(), 'Other_Name'] = df[~df['Other_Name'].isnull()]['Other_Name'].apply(change_key)
print(df)
推荐阅读
- python - 如何从频道 ID 中获取频道对象?
- python - mysql-connector-python 导入的问题
- python - 查找从 1 个数组拆分的 2 个子数组的最大乘积
- python - 你可以用python打开命令提示符吗?
- javascript - 不和谐反应角色问题
- reactjs - 带有 Expo + 反应导航 5 的 Firebase 身份验证流程
- python - pip install 无法识别以前安装的软件包
- browserify - 尝试浏览化超群库以从浏览器连接到主题
- c# - Automapper C# Net Core - 如何映射两个不同结构的列表来更改一个字段的值?
- html - 将鼠标悬停在另一个div中的元素上时如何在一个div中显示元素