Pandas:通过“A 列"应用函数,同时读取“B 列" [英] Pandas: Apply function via "Column A", simultaneously reading "Column B"

查看:49
本文介绍了Pandas:通过“A 列"应用函数,同时读取“B 列"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Pandas 来驱动一个 Python 函数.在 inputs.csv 中,我使用 "Column A" 中的每一行作为函数的输入.

I'm using Pandas to drive a Python function. From inputs.csv, I use each row in "Column A" as an input for the function.

csv 中,还有一个 "Column B" 包含我想读入变量 x 中的值功能.它不应该从 "Column B" apply - 这仍然应该从 "Column A" 完成.这可能吗?

In the csv, there is also a "Column B" that contains values that I want to read into a variable x within the function. It should not apply from "Column B" – this should still be done from "Column A". Is this possible?

这是应用A列"中的函数的当前代码:

This is the current code that applies the function from "Column A":

import pandas as pd
df = pd.read_csv(inputs.csv, delimiter=",")

def function(a):
    #variables c, d, e are created here
    ###I would like to create x from Column B if possible
    return pd.Series([c, d, e])
df[["Column C", "Column D", "Column E"]] = df["Column A"].apply(function)

<小时>

后期编辑:此问题可能与另一个问题重复.尽管答案可能相同,问题却不尽相同.对于未来的读者来说,两列上的 apply 可以与一列上的 apply 互换并同时阅读"另一列,这可能并不明显.因此,这个问题应该保持开放.


Post-edit: This question has been identified as a possible duplicate of another question. Although the answer may be the same, the question is not the same. For future readers it is probably not apparent that apply on two columns is interchangeable with apply on one column and "reading" another column at the same time. The question should therefore remain open.

推荐答案

是的,您目前正在使用 Series.apply() ,而您可以使用 - DataFrame.apply()axis=1 获取函数中的每一行,然后您可以访问列 - row[].

Yes, you are currently using Series.apply() , instead you can use - DataFrame.apply(), with axis=1 to get each row in the function , then you can access the columns as - row[<column>].

示例 -

In [37]: df
Out[37]:
   X  Y  Count
0  0  1      2
1  0  1      2
2  1  1      2
3  1  0      1
4  1  1      2
5  0  0      1

In [38]: def func1(r):
   ....:     print(r['X'])
   ....:     print(r['Y'])
   ....:     return r
   ....:

In [39]: df.apply(func1,axis=1)
0
1
0
1
1
1
1
0
1
1
0
0
Out[39]:
   X  Y  Count
0  0  1      2
1  0  1      2
2  1  1      2
3  1  0      1
4  1  1      2
5  0  0      1

这只是一个非常简单的例子,你可以将它修改成你真正想做的事情.

This is just a very simple example, you can modify this to what you really want to do.

这篇关于Pandas:通过“A 列"应用函数,同时读取“B 列"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆