В вашем вопросе есть немного двусмысленности. Существует не менее трех двух интерпретаций:
di
относятся к значениям индекса di
относятся к df['col1']
значениям di
относятся к местоположению индексов (а не к вопросу OP, но выбрасываются для удовольствия.) Ниже приведено решение для каждого случая.
Случай 1: Если клавиши di
предназначены для обозначения значений индекса, вы можете использовать метод update
:
df['col1'].update(pd.Series(di))
Например,
import pandas as pd
import numpy as np
df = pd.DataFrame({'col1':['w', 10, 20],
'col2': ['a', 30, np.nan]},
index=[1,2,0])
# col1 col2
# 1 w a
# 2 10 30
# 0 20 NaN
di = {0: "A", 2: "B"}
# The value at the 0-index is mapped to 'A', the value at the 2-index is mapped to 'B'
df['col1'].update(pd.Series(di))
print(df)
дает
col1 col2
1 w a
2 B 30
0 A NaN
Я изменил значения из вашего исходного сообщения, чтобы было ясно, что делает update
. Обратите внимание, что ключи из di
связаны с значениями индекса. Порядок значений индекса, т. Е. Индекс местоположения - не имеет значения.
Случай 2: Если клавиши в di
относятся к df['col1']
, то @DanAllan и @DSM показывают, как достичь этого с помощью replace
:
import pandas as pd
import numpy as np
df = pd.DataFrame({'col1':['w', 10, 20],
'col2': ['a', 30, np.nan]},
index=[1,2,0])
print(df)
# col1 col2
# 1 w a
# 2 10 30
# 0 20 NaN
di = {10: "A", 20: "B"}
# The values 10 and 20 are replaced by 'A' and 'B'
df['col1'].replace(di, inplace=True)
print(df)
дает
col1 col2
1 w a
2 A 30
0 B NaN
Обратите внимание, как в этом случае клавиши в di
были изменены в соответствии с значениями в df['col1']
.
Случай 3: Если клавиши в di
относятся к местоположениям индекса, вы можете использовать
df['col1'].put(di.keys(), di.values())
, поскольку
df = pd.DataFrame({'col1':['w', 10, 20],
'col2': ['a', 30, np.nan]},
index=[1,2,0])
di = {0: "A", 2: "B"}
# The values at the 0 and 2 index locations are replaced by 'A' and 'B'
df['col1'].put(di.keys(), di.values())
print(df)
дает
col1 col2
1 A a
2 10 30
0 B NaN
Здесь первая и третья строки были изменены, поскольку клавиши в di
являются 0
] и 2
, которые с индексом на основе индекса Python относятся к первому и третьему местоположениям.
Я должен был изменить контроллер. Я добавил еще одну функцию под названием «iedit», чем в iedit.html.twig, которую я назвал «duyurular_fotoekle». Если вы не могли понять, что я сделал, не стесняйтесь спрашивать.
/**
* @Route("/{id}/fotoekle", name="duyurular_fotoekle", methods={"POST"})
*/
public function fotoekle(Request $request, Duyurular $duyurular, $id): \Symfony\Component\HttpFoundation\RedirectResponse
{
$form = $this->createForm(DuyurularType::class, $duyurular);
$form->handleRequest($request);
echo ('sefa 2');
$file = $request->files->get('image');
// $file = $duyurular->getFotograf();
// $file = $form->get('fotograf')->getData();
$fileName = $this->generateUniqueFileName().'.'.$file->guessExtension();
try{
$file->move(
$this->getParameter('fotograflar_directory'),
$fileName
);
}catch (FileException $e){
}
$duyurular->setFotograf($fileName);
$this->getDoctrine()->getManager()->flush();
return $this->redirectToRoute('duyurular_iedit', ['id' => $duyurular->getId(),]);
}
/**
* @Route("/{id}/iedit", name="duyurular_iedit", methods="GET|POST")
*/
public function iedit(Request $request,$id, Duyurular $duyurular,DuyurularRepository $duyurularRepository): Response
{
$duyurulist = $duyurularRepository ->findAll();
$duyuruname = $duyurularRepository ->findBy(['id'=> $duyurular->getId()]);
$form = $this->createForm(DuyurularType::class, $duyurular);
$form->handleRequest($request);
echo ('sefa 0');
$this->getDoctrine()->getManager()->flush();
if ($form->isSubmitted()) {
echo ('sefa 1');
return $this->redirectToRoute('duyurular_index', ['id' => $duyurular->getId()]);
}
return $this->render('duyurular/iedit.html.twig', [
'duyurular' => $duyurular,
'id'=>$id,
'duyurulist' => $duyurulist,
'duyuruname' => $duyuruname,
'form' => $form->createView(),
]);
}