繁体   English   中英

Pandas DataFrame 中的逐行操作

[英]Row wise operation in Pandas DataFrame

我有一个 Dataframe 作为

import pandas as pd
df = pd.DataFrame({
  "First": ['First1', 'First2', 'First3'],
  "Secnd": ['Secnd1', 'Secnd2', 'Secnd3']
)
df.index = ['Row1', 'Row2', 'Row3']

我想在apply方法中有一个lambda function 来创建字典列表(包括索引项),如下所示

[
  {'Row1': ['First1', 'Secnd1']},
  {'Row2': ['First2', 'Secnd2']},
  {'Row3': ['First3', 'Secnd3']},
]

如果我在这里使用.apply(lambda x: <some operation>)之类的东西, x不包括索引而是值。

干杯,DD

你不需要在这里申请。 您可以将 to_dict() function 与“index”参数一起使用:

df.to_dict("index")

这给出了 output:

{'Row1': {'First': 'First1', 'Secnd': 'Secnd1'}, 
'Row2': {'First': 'First2', 'Secnd': 'Secnd2'}, 
'Row3': {'First': 'First3', 'Secnd': 'Secnd3'}}

要扩展 Hans Bambel 的答案以获得确切所需的 output:

[{k: list(v.values())} for k, v in df.to_dict('index').items()]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM