Python 如何按名称为特定行和列指定值?
我尝试遍历数据帧中的每一行,并为此-Python 如何按名称为特定行和列指定值?,python,pandas,Python,Pandas,我尝试遍历数据帧中的每一行,并为此-计算距离(row),然后重新分配返回值(它是一个数字)。 结果是它没有保存特定列下的值,我缺少什么 例如: DF示例 我想对每一行执行这个函数C=A+B,并达到这个状态: A B C 1 10 11 2 12 14 我这样做: def calculate_distance_from_SnS(row): 使用DF行和2列进行计算 for i,row in customers.iterrows(): row['dist_fro
计算距离(row)
,然后重新分配返回值(它是一个数字)。
结果是它没有保存特定列下的值,我缺少什么
例如:
DF示例
我想对每一行执行这个函数C=A+B
,并达到这个状态:
A B C
1 10 11
2 12 14
我这样做:
def calculate_distance_from_SnS(row):
使用DF行和2列进行计算
for i,row in customers.iterrows():
row['dist_from_sns'] = calculate_distance_from_SnS(row)
设置原始
数据帧
,而不是循环中的系列
:
for i,row in customers.iterrows():
customers.loc[i, 'dist_from_sns'] = calculate_distance_from_SnS(row)
但如果可能,最好与轴=1一起使用,以便按行处理:
f = lambda x: calculate_distance_from_SnS(x['lat'], x['long'])
customers['dist_from_sns'] = customers.apply(f, axis=1)
你的第一个解决方案成功了!,但是我不理解第二个,关于:客户['cols'].apply(计算距离),我使用的列是“lat”和“lng”,所以应该是:客户['dist\u from\u SnS']=customers['lat','long']。apply(计算距离)或者我错了?@Daniel-为apply添加了解决方案,
iterrows
working,但如果存在一些替代方案,最好避免它-检查
f = lambda x: calculate_distance_from_SnS(x['lat'], x['long'])
customers['dist_from_sns'] = customers.apply(f, axis=1)