如何修剪dataframe列中的列表

2024-04-18 03:11:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Python/熊猫有点陌生

我将json转换为csv。现在有一列仍然像这样,并且包含几个属性

                                            location
0  {'country': 'United States', 'state': 'New Jer...
1  {'country': 'Australia', 'state': 'Queensland'...
2  {'country': 'United States', 'state': 'Texas',...
3  {'country': 'Australia', 'state': None, 'city'...
4  {'country': 'United States', 'state': 'Califor...

基本上,我想要的是一个简单的列,只包含作为字符串的country值。所以看起来有点像这样:

        location
0  United States
1  Australia
2  United States
3  Australia
4  United States

非常感谢您的帮助


Tags: csvnonejsonnew属性locationcountryunited
3条回答

如果列由字典填充,请使用:

print (type(df.loc[0, 'location']))
<class 'dict'>

df['location'] = df['location'].str.get('country')
print (df)
        location
0  United States
1      Australia
2  United States
3      Australia
4  United States

如果有字符串:

print (type(df.loc[0, 'location']))
<class 'str'>

import ast

df['location'] = df['location'].apply(ast.literal_eval).str.get('country')

print (df)
        location
0  United States
1      Australia
2  United States
3      Australia
4  United States

直接阅读Json,如下所示:

import pandas as pd
df = pd.read_json ('jsnotation.json')

df现在是一个数据帧。因此,打印将提供以下输出:

    Country    State
0   USA        Texas
1   Australia  Qeensland
2   USA        California

现在,您可以获得所需的结果,如:

print(df['country'])

   Country    
0   USA       
1   Australia 
2   USA       

要更改标题,请执行以下操作:

df = df.rename(columns={'Country': 'Location'})

您可以直接从具有类似键的字典列表构建数据帧。因此,在构建新数据框之前,只需将列中的项转换为列表形式。dict列表中的键成为新列

这可以用一行代码来解决-

df = pd.DataFrame({'Location':[{'country': 'United States', 'state': 'New Jersey'},
                               {'country': 'Australia', 'state': 'Queensland'},
                               {'country': 'United States', 'state': 'Texas'}]})


#Building a dataframe directly from a list of dictionaries with similar keys
df2 = pd.DataFrame(list(df['Location'].values))
print(df2)
         country       state
0  United States  New Jersey
1      Australia  Queensland
2  United States       Texas

相关问题 更多 >