我有一个这样的数据帧:
name: ... line:
bobo ... 10
amy ... 5
amanda ... 15
我正在使用以下代码:
def test_function(df_test, column_name):
for index, row in df_test.iterrows():
input = row[column_name]
df_test['col1'] = input * 1
df_test['col2'] = input * 5
df_test['col3'] = input * 10
return df_test
我希望col1、col2和col3的每个结果列都有基于其行['column_name]的值,但它们都被分配了最后一个值,而不是迭代分配。
我正在调用函数:
test_function(df_test, 'line')
当前返回的内容:
name: ... line: col1: col2: col3:
bobo ... 10 15 75 150
amy ... 5 15 75 150
amanda ... 15 15 75 150
我想要退货:
name: ... line: col1: col2: col3:
bobo ... 10 10 50 100
amy ... 5 5 25 50
amanda ... 15 15 75 150
有人知道我做错了什么吗?
谢谢!
在for
循环的每次迭代中都要重新分配整个列。分配时需要同时指定索引和列。试试这个:
def test_function(df_test, column_name):
for i in df.index:
df_test.at[i, "col1"] = df_test.at[i, column_name]
df_test.at[i, "col2"] = df_test.at[i, column_name]*5
df_test.at[i, "col3"] = df_test.at[i, column_name]*10
return df_test
>>> test_function(df, "line")
name line col1 col2 col3
0 bobo 10 10.0 50.0 100.0
1 amy 5 5.0 25.0 50.0
2 amanda 15 15.0 75.0 150.0
或者,对于您的特定情况,您甚至不需要对每一行进行迭代。您可以一次将整列相乘,如下所示:
def test_function(df_test, column_name):
df_test["col1"] = df_test[column_name]*1
df_test["col2"] = df_test[column_name]*5
df_test["col3"] = df_test[column_name]*10
return df_test
>>> test_function(df, "line")
name line col1 col2 col3
0 bobo 10 10 50 100
1 amy 5 5 25 50
2 amanda 15 15 75 150
如果您只想内联,另一种可能的方法是:
import pandas as pd
df = pd.DataFrame({
'name':['bobo','amy','amanda'],
'line':[10,5,15]})
df[['col1','col2','col3']] = df['line'].apply(lambda x: pd.Series([x*n for n in [1,5,10]]))