我想在python pandas中为一个系列应用带参数的函数:
x = my_series.apply(my_function, more_arguments_1)
y = my_series.apply(my_function, more_arguments_2)
...
Run Code Online (Sandbox Code Playgroud)
该文档描述了对apply方法的支持,但它不接受任何参数.是否有接受参数的不同方法?或者,我错过了一个简单的解决方法吗?
更新(2017年10月): 请注意,由于此问题最初被要求apply()已更新pandas 以处理位置和关键字参数,上面的文档链接现在反映了这一点并显示了如何包含任一类型的参数.
我在Pandas中"应用"自定义函数时遇到了麻烦.当我测试函数时,直接传递它工作的值并正确返回响应.但是,当我尝试传递列值时,我收到错误"系列的真值是不明确的.使用a.empty,a.bool(),a.item(),a.any()或a.所有()."
def feez (rides, plan):
pmt4 = 200
inc4 = 50 #number rides included
min_rate4 = 4
if plan == "4 Plan":
if rides > inc4:
fee = ((rides - inc4) * min_rate4) + pmt4
else:
fee = pmt4
return (fee)
else:
return 0.1
df['fee'].apply(feez(df.total_rides, df.plan_name))
Run Code Online (Sandbox Code Playgroud)
直接传递值,即feez(800,"4 Plan"),返回3200
但是,当我尝试应用上述功能时,我收到错误.
我是新手,怀疑我的语法写得不好.任何想法都非常感激.TIA.礼
我有 500,000 个纬度和经度坐标列表,如下所示:
Latitude Longitude
42.022506 -88.168156
41.877445 -87.723846
29.986801 -90.166314
Run Code Online (Sandbox Code Playgroud)
我希望使用 python 来获取新列中每个坐标的城市、州和国家/地区,如下所示:
Latitude Longitude City State Country
42.022506 -88.168156 Streamwood IL United States
41.877445 -87.723846 Chicago IL United States
29.986801 -90.166314 Metairie LA United States
Run Code Online (Sandbox Code Playgroud)
这么大的数据集,如何用Python实现呢?我听说过 Google 的 API、Nominatim 的 API 和 Geopy 包。
我如何才能将所有行运行到这段代码中?现在我必须在最后一行手动输入纬度和经度。
import csv
import pandas as pd
import numpy as np
import math
from geopy.geocoders import Nominatim
input_file = "Lat-Log.csv" # file contains ID, Latitude, Longitude
output_file = "output.csv"
df = pd.read_csv(input_file)
geolocator = …Run Code Online (Sandbox Code Playgroud) 说我有一个映射:
mapping = {
'cat': 'purrfect',
'dog': 'too much work',
'fish': 'meh'
}
Run Code Online (Sandbox Code Playgroud)
和a dataframe:
animal name description
0 cat sparkles NaN
1 dog rufus NaN
2 fish mr. blub NaN
Run Code Online (Sandbox Code Playgroud)
我想以编程方式description使用animal列和mappingdict作为输入填写列:
def describe_pet(animal,mapping):
return mapping[animal]
Run Code Online (Sandbox Code Playgroud)
当我尝试使用pandas apply()功能时:
df['description'].apply(describe_pet,args=(df['animal'],mapping))
Run Code Online (Sandbox Code Playgroud)
我收到以下错误:
TypeError: describe_pet() takes exactly 2 arguments (3 given)
Run Code Online (Sandbox Code Playgroud)
似乎使用apply()是很简单的将一个参数传递给函数.我怎么能用两个参数做到这一点?