Как правильно установить несколько столбцов в Pandas из списка? ⇐ Python
-
Anonymous
Как правильно установить несколько столбцов в Pandas из списка?
This must be burried somewhere in Pandas docs but I think I am so overwhelmed at this point, I can't find the right doc page. I have some code that worked with python3.9 pandas==1.4.3/numpy==1.23.1 but recently started failing with the newer version on python3.11 pandas==2.2.1/numpy==1.26.4.
I have some multi-column results in pd.Series that I want to set to the same number of columns inside pd.DataFrame. If I have code similar to:
from unittest.mock import MagicMock import pandas as pd def test_assign_results() -> None: df = pd.DataFrame([{"is_ok": True, "failed": None, "col1": None, "col2": None}]) m1 = MagicMock() m1.name = "col1_val" results = pd.Series([(m1, None)]) df.loc[df["is_ok"] == 1, ["col1", "col2"]] = results.to_numpy().tolist() row = df.iloc[0] assert row["col1"].name == "col1_val" assert row["col2"] is None The code used to work like this before but now it results in the error: AttributeError: 'list' object has no attribute 'ndim'
I suspect this code was brittle to begin with, so what would be the correct way to take 2 values and assign them to 2 columns within a DataFrame?
Источник: https://stackoverflow.com/questions/780 ... rom-a-list
This must be burried somewhere in Pandas docs but I think I am so overwhelmed at this point, I can't find the right doc page. I have some code that worked with python3.9 pandas==1.4.3/numpy==1.23.1 but recently started failing with the newer version on python3.11 pandas==2.2.1/numpy==1.26.4.
I have some multi-column results in pd.Series that I want to set to the same number of columns inside pd.DataFrame. If I have code similar to:
from unittest.mock import MagicMock import pandas as pd def test_assign_results() -> None: df = pd.DataFrame([{"is_ok": True, "failed": None, "col1": None, "col2": None}]) m1 = MagicMock() m1.name = "col1_val" results = pd.Series([(m1, None)]) df.loc[df["is_ok"] == 1, ["col1", "col2"]] = results.to_numpy().tolist() row = df.iloc[0] assert row["col1"].name == "col1_val" assert row["col2"] is None The code used to work like this before but now it results in the error: AttributeError: 'list' object has no attribute 'ndim'
I suspect this code was brittle to begin with, so what would be the correct way to take 2 values and assign them to 2 columns within a DataFrame?
Источник: https://stackoverflow.com/questions/780 ... rom-a-list