我正在使用 Pandas
来驱动 Python
函数。在 inputs.csv
中,我使用 “Column A”
中的每一行作为函数的输入。
在 csv
中,还有一个 “Column B”
,其中包含我想读入变量 x
的值功能。它不应该从 “Column B”
apply
– 这仍然应该从 “Column A”
完成。这可能吗?
这是应用“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)
后期编辑:此问题已被确定为可能与 another question 重复.虽然答案可能相同,但问题却不一样。对于 future 的读者来说,两列上的 apply
与一列上的 apply
并同时“读取”另一列是可以互换的,这可能并不明显。因此,这个问题应该保持开放。
最佳答案
是的,您当前正在使用 Series.apply()
, 而不是你可以使用 - DataFrame.apply()
, 与 axis=1
获取函数中的每一行,然后您可以访问这些列 - 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
这只是一个很简单的例子,你可以修改成你真正想做的。
关于python - Pandas :通过 "Column A"应用函数,同时读取 "Column B",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31825834/