基本的熊猫数据框操作问题

时间:2021-04-03 12:10:28

标签: python pandas

我有以下 JSON 片段:

async function allKeyed(promises) {
    // Get an array of [name, value] pairs for the object's properties
    const entries = Object.entries(promises);
    // Wait for any thenables/promises in the values to settle
    const values = await Promise.all(entries.map(([_, value]) => value));
    // Build an object from those result values; this works because the
    // array from `Promise.all` is in the same order as the array of
    // values we gave it above.
    const result = Object.fromEntries(entries.map(([key], index) => {
        return [key, values[index]];
    }));
    return result;
}

function fetchSomething(value) {
    return new Promise(resolve => {
        setTimeout(() => {
            console.log(`fulfilling with ${value}`);
            resolve(value);
        }, Math.floor(Math.random() * 1000));
    });
}

(async () => {
    let result1 = fetchSomething("one");
    let result2 = fetchSomething("two");
    let result3 = fetchSomething("three");
    ({result3, result1, result2} = await allKeyed({result1, result2, result3}));

    console.log({result1, result2, result3});
})()
.catch(error => console.error(error));

我感兴趣的信息都在 {'search_metadata': {'completed_in': 0.027, 'count': 2}, 'statuses': [{'contributors': None, 'coordinates': None, 'created_at': 'Wed Mar 31 19:25:16 +0000 2021', 'text': 'The text', 'truncated': True, 'user': {'contributors_enabled': False, 'screen_name': 'abcde', 'verified': false } } ,{...}] } 数组中。有了熊猫,我可以把它变成这样的 DataFrame

statuses

然后我从这个数据框中提取一个子集

df = pd.DataFrame(Data['statuses']) 

dfsub = df[['created_at', 'text']] 完全符合我的预期。

但我也想将 display(dfsub) 包含到子集中。

[user][screen_name]

在语法上是正确的,但 dfs = df[[ 'user', 'created_at', 'text']] 包含太多信息。

如何只将 user 添加到子集? 我尝试过类似以下的方法,但都没有效果

screen_name

3 个答案:

答案 0 :(得分:3)

我会在构建 DataFrame 之前对数据进行标准化。 看看这里:https://stackoverflow.com/a/41801708/14596032

工作示例作为您问题的答案:

df = pd.json_normalize(Data['statuses'], sep='_')
dfs = df[[ 'user_screen_name', 'created_at', 'text']]
print(dfs)

答案 1 :(得分:0)

您可以使用 pd.Series.str。文档并没有对 .str 可以做的所有美妙的事情做出公正的评价,例如访问 listdict 项目。例如,您可以像这样访问 dict 元素:

df['user'].str['screen_name']

也就是说,我同意 @VladimirGromes 的观点,即更好的方法是将数据规范化为平面表。

答案 2 :(得分:0)

你可以尝试访问Dataframe,然后是Series,然后是Dict

df['user']                   # user column = Series
df['user'][0]                # 1st (only) item of the Series = dict
df['user'][0]['screen_name'] # screen_name in dict