问题
I need to create a new column at the end of a data frame, where the values in that new column are the result of applying some function who's parameters are based on other columns. Specifically, from another column, but a different row. So for example, if my data frame had two columns, containing values x_i
, y_i
respectively, my third column would be f(x_(i-1), y_(i-1))
I know that to create create a new column, the easiest way would be to do something like
df['new_row'] = ...
But I'm not sure what I can set to that.
How do I do this?
回答1:
Something like this? Or is your function more complicated?
print(df)
0 1 2 3
0 1 2 3 4
df[4]= df[2]*df[3]/.3
print(df)
0 1 2 3 4
0 1 2 3 4 40
回答2:
Here's an example:
df['new_col'] = df['old_col'] * df['old_col']
Or if you wrote a custom function that took in two arrays, such as:
def f(arr1, arr2):
new_arr = # put logic here
return newer
You could try:
df['new_col'] = f(df['old_col'], df['old_col2'])
回答3:
1 3
3 3
43 4
2 3
with open("file", 'r') as f:
for line in f:
n, r = line.split()
formula = pow(int(n),int(r))
print("{:4}{:4}{:9}".format(n,r, formula))
output
1 3 1
3 3 27
43 4 3418801
2 3 8
来源:https://stackoverflow.com/questions/32752087/pandas-how-to-create-a-column-based-on-values-of-another-column