1

JSON我想将其放入数据框中有些棘手。

{'A': {'name': 'A',
  'left_foot': [{'toes': '5'}],
  'right_foot': [{'toes': '4'}]},
 'B': {'name': 'B',
  'left_foot': [{'toes': '3'}],
  'right_foot': [{'toes': '5'}]},
...
}

我不需要带有 A 和 B 的第一层,因为它是名称的一部分。永远只有一个 left_foot 和一个 right_foot。

我想要的数据如下:

     name  left_foot.toes right_foot.toes
0       A           5           4
1       B           3           5

使用这篇文章能够得到脚和脚趾,但如果你说数据[“A”]。有没有更简单的方法?

编辑 我有这样的东西,但我需要"A"在第一行指定。

df = pd.json_normalize(tickers["A"]).pipe(
    lambda x: x.drop('left_foot', 1).join(
        x.left_foot.apply(lambda y: pd.Series(merge(y)))
    )
).rename(columns={"toes": "left_foot.toes"}).pipe(
    lambda x: x.drop('right_foot', 1).join(
        x.right_foot.apply(lambda y: pd.Series(merge(y)))
    )).rename(columns={"toes": "right_foot.toes"})
4

1 回答 1

2
  • 给定您的数据,每个顶层key(例如'A''B')都重复为valuein 'name',因此pandas.json_normalize仅在values的上使用会更容易dict
  • 'left_foot''right_foot'需要被分解以dictlist
  • 最后一步将 的列转换为dicts数据框并将其连接回df
  • 它不一定是更少的代码,但这应该比当前代码中使用的多个应用要快得多。
    • 请参阅此时序分析apply pandas.Seriespandas.DataFrame用于转换列的比较。
  • 如果由于您的数据框在要分解并转换为数据框的列中有NaN(例如缺少dicts或)而出现问题,请参阅如何使用 NaN 对列进行 json_normalizelists
import pandas as pd

# test data
data = {'A': {'name': 'A', 'left_foot': [{'toes': '5'}], 'right_foot': [{'toes': '4'}]}, 'B': {'name': 'B', 'left_foot': [{'toes': '3'}], 'right_foot': [{'toes': '5'}]}, 'C': {'name': 'C', 'left_foot': [{'toes': '5'}], 'right_foot': [{'toes': '4'}]}, 'D': {'name': 'D', 'left_foot': [{'toes': '3'}], 'right_foot': [{'toes': '5'}]}}

# normalize data.values and explode the dicts out of the lists
df = pd.json_normalize(data.values()).apply(pd.Series.explode).reset_index(drop=True)

# display(df)
  name      left_foot     right_foot
0    A  {'toes': '5'}  {'toes': '4'}
1    B  {'toes': '3'}  {'toes': '5'}
2    C  {'toes': '5'}  {'toes': '4'}
3    D  {'toes': '3'}  {'toes': '5'}

# extract the values from the dicts and create toe columns
df = df.join(pd.DataFrame(df.pop('left_foot').values.tolist())).rename(columns={'toes': 'lf_toes'})
df = df.join(pd.DataFrame(df.pop('right_foot').values.tolist())).rename(columns={'toes': 'rf_toes'})

# display(df)
  name lf_toes rf_toes
0    A       5       4
1    B       3       5
2    C       5       4
3    D       3       5
于 2021-01-23T03:27:43.517 回答