python - 对 Pandas 数据框中的行对应用函数

标签 python pandas

我是 pandas dataframe 的新手,我想应用一个在同一列中获取几行的函数。就像当您应用函数 diff() 时一样,但我想计算文本之间的距离。所以我定义了一个测量距离的函数,我尝试使用 apply 但我不知道如何选择几行。下面我展示了一个我尝试做的示例以及我的期望:

def my_measure_function(x,y):
   return some_distance_calculus(x,y)

>>> from pandas import DataFrame
>>> df = DataFrame({"text": ['hello','hella','hel'], "B": [3,4,4]})
>>> df['dist'] = df.apply(lambda x, y: my_measure_function(x, y), axis=0)

但它不起作用。 我想要获得的是:

>>> df
      text  B  dist
0    hello  3    0
1    hella  4    1
2    hel    4    2

预先感谢您为我提供的任何帮助。

最佳答案

您可能希望避免pd.DataFrame.apply ,如performance may suffer 。相反,您可以将 mappd.Series.shift 一起使用。 :

df['dist'] = list(map(my_measure_function, df['text'], df['text'].shift()))

或者通过列表理解:

zipper = zip(df['text'], df['text'].shift())
df['dist'] = [my_measure_function(val1, val2) for val1, val2 in zipper]

关于python - 对 Pandas 数据框中的行对应用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52711358/

相关文章:

python - 无法将输入发送到 Sublime Text 中正在运行的程序

python - 为什么这种模拟退火算法应用于TSP不收敛?

python - df.duplicated() 误报?

python - 下载多个 PDF 时出现问题

python - 如何在Flask python应用程序中运行Elasticsearch的实例?

python - SQLAlchemy/pandas to_sql for SQLServer——在主数据库中创建表

python-3.x - 在 Pandas 中将字符串转换为日期时间时发出

python - 根据条件从数据帧创建 python 列表

python - 加入多索引的pandas系列

python - Scipy 排名数据从高到低反转