2

Есть DataFrame, один из столбцов (Series) которого содержит 5000 ячеек вида:

[{"credit_id": "52fe48009251416c750aca23", "department": "Editing", 
"gender": 0, "id": 1721, "job": "Editor", "name": "Stephen E. Rivkin"}, 
{"credit_id": "539c47ecc3a36810e3001f87", "department": "Art", "gender": 
2, "id": 496, "job": "Production Design", "name": "Rick Carter"}, 
{"credit_id": "54491c89c3a3680fb4001cf7", "department": "Sound", 
"gender": 0, "id": 900, "job": "Sound Designer", "name": "Christopher 
Boyes"}]

Я хочу создать отдельный столбец (в том же DataFrame), содержащий, например, значение имени Sound Designer.

Для этого создаю и применяю к существующему столбцу функцицю:

def producer(line):
    name = json.loads(line)
    return name[2]['name']

однако ответ при любом индексе:

list index out of range

При этом, если я беру отдельную ячейку столбца, то такой подход работает. Как я понимаю, Pandas не умеет извлекать из ячеек элементы из структуры JSON, либо же модель JSON не работает в рамках элементов Pandas?

10
  • Приведенная в качестве примера JSON строка - это пример содержимого одной ячейки или это значения данного столбца для трех строк? 6 окт 2019 в 12:49
  • что выдает type(df["column_name"].iloc[0]) ? 6 окт 2019 в 12:56
  • Приведенный пример это содержание одной ячейки. Тип данных в ячейке - str
    – Dmitriy
    6 окт 2019 в 13:25
  • С такими данными очень неудобно работать. Как вы получили данный DataFrame? Я думаю будет гораздо легче распарсить данные до того или во время того как создаете DataFrame... 6 окт 2019 в 13:29
  • К сожалению, датафрейм - это данность, первичный источник информации, и данные в ячейке имеют строковые значения, но структурированы по типу JSON.
    – Dmitriy
    6 окт 2019 в 13:34

1 ответ 1

2

Попробуйте так:

fn = r"D:\download\tmdb_5000_credits.csv"

raw = pd.read_csv(fn)

cast_data = raw["cast"].map(json.loads).to_dict()
crew_data = raw["crew"].map(json.loads).to_dict()

crew = pd.concat(
    [pd.DataFrame(crew_data[idx]).assign(idx=idx) for idx in crew_data],
    ignore_index=True, 
    sort=False)

Значения столбца idx в crew будут соответствовать значению индекса в raw DataFrame:

In [122]: crew
Out[122]:
                       credit_id  department  gender        id                       job               name   idx
0       52fe48009251416c750aca23     Editing     0.0    1721.0                    Editor  Stephen E. Rivkin     0
1       539c47ecc3a36810e3001f87         Art     2.0     496.0         Production Design        Rick Carter     0
2       54491c89c3a3680fb4001cf7       Sound     0.0     900.0            Sound Designer  Christopher Boyes     0
3       54491cb70e0a267480001bd0       Sound     0.0     900.0  Supervising Sound Editor  Christopher Boyes     0
4       539c4a4cc3a36810c9002101  Production     1.0    1262.0                   Casting          Mali Finn     0
5       5544ee3b925141499f0008fc       Sound     2.0    1729.0   Original Music Composer       James Horner     0
6       52fe48009251416c750ac9c3   Directing     2.0    2710.0                  Director      James Cameron     0
...                          ...         ...     ...       ...                       ...                ...   ...
129574  52fe4ad9c3a368484e16a36b   Directing     2.0  208138.0                  Director        Daniel Hsia  4801
129575  52fe4ad9c3a368484e16a371     Writing     2.0  208138.0                    Writer        Daniel Hsia  4801
129576  58ce021b9251415a390165d9  Production     2.0    6888.0        Executive Producer     Clark Peterson  4802
129577  58ce0232c3a36850e90157da  Production     2.0   61051.0        Executive Producer      Andrew Reimer  4802
129578  52fe44e8c3a368484e03da8d   Directing     2.0   85563.0                  Director   Brian Herzlinger  4802
129579  52fe44e8c3a368484e03da87   Directing     2.0   94471.0                  Director           Jon Gunn  4802
129580  52fe44e8c3a368484e03da97   Directing     0.0  997560.0                  Director         Brett Winn  4802

[129581 rows x 7 columns]

теперь можем искать всех 'Sound Designer':

In [121]: crew.query("job == 'Sound Designer'")
Out[121]:
                       credit_id department  gender         id             job                 name   idx
2       54491c89c3a3680fb4001cf7      Sound     0.0      900.0  Sound Designer    Christopher Boyes     0
200     5677dd1ec3a36816890085d3      Sound     0.0    14764.0  Sound Designer  Christopher Assells     2
249     5677dd38c3a368167c008c21      Sound     0.0  1392083.0  Sound Designer         Ann Scibelli     2
263     5677dd519251417845001588      Sound     0.0  1404217.0  Sound Designer        Peter Staubli     2
408     54c273cf92514124ed003c05      Sound     2.0  1341403.0  Sound Designer         Richard King     3
624     58c69a7ac3a368410c016254      Sound     0.0  1394129.0  Sound Designer          Tim Nielsen     4
777     572bc9fb925141388500012e      Sound     2.0  1424167.0  Sound Designer     Cameron Frankley     6
...                          ...        ...     ...        ...             ...                  ...   ...
128030  599f16fcc3a3683f4f001b75      Sound     0.0  1876239.0  Sound Designer        Tommy Persson  4591
128142  52fe423dc3a36847f800ec85      Sound     2.0     5265.0  Sound Designer     James A. Gleason  4602
128271  52fe48e29251416c750b6589      Sound     0.0  1043429.0  Sound Designer        Robert Rubin   4618
128738  599ee27dc3a36859ed011519      Sound     0.0  1111128.0  Sound Designer      Knud Kristensen  4686
128828  54905c85925141220b001c2e      Sound     0.0  1073059.0  Sound Designer        Ryan M. Price  4700
129181  52fe48ddc3a368484e10f029      Sound     0.0   583474.0  Sound Designer        Richard Ragon  4748
129453  554c850992514140c300145a      Sound     2.0   960074.0  Sound Designer     Keith Bilderbeck  4783

[885 rows x 7 columns]

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.