Reputation: 912
My dataset has this format, 3 columns and some unique variables
A = [A1, A2, A3, A4]
B = [B1, B2, B3]
C = [C1, C2, C3, C4, C5]
I want to call a specific variable, and then assign a value to it.
Example 1:
A B C
A2 B3 C5
A1 B2 C2
A3 B1 C4
A4 B2 C3
A2 B3 C1
Call all [A1, B2, C3] and assign them to be equal to [1, 2,3]
A B C
A2 B3 C5
1 2 C2
A3 B1 C4
A4 2 3
A2 B3 C1
@Scott Boston suggested using dictionary to assign the value in this way
Example 2: I want to assign the value one by one in a loop, such as A1 first, then do some calculation, then assign A2, and so on. Then how can I do that?
Thank you in advance
Upvotes: 2
Views: 1458
Reputation: 237
For the second part of your answer I believe apply()
function of pandas will be a more efficient solution.
Eg:
def my_func(a):
#your computation here
df['A'].apply(lambda x: my_func(x))
Upvotes: 0
Reputation: 368
As for your 2nd example, where you want to assign values iteratively, you an do it this way.
var = ['A1','B2','C3']
val = [1,2,3]
for i in range(len(val)):
df = df.replace({var[i]:val[i]})
# your calculations here...
Upvotes: 1
Reputation: 153500
IIUC, use replace
with dictionary:
print(df)
Output:
A B C
0 A2 B3 C5
1 A1 B2 C2
2 A3 B1 C4
3 A4 B2 C3
4 A2 B3 C1
Create a dictionary for replacement.
d = {'A1':1,'B2':2,'C3':3}
@Wen suggest using this statement to create dictionary:
d=dict(zip( ['A1', 'B2', 'C3'],[1,2,3] ))
df_out = df.replace(d)
print(df_out)
Output:
A B C
0 A2 B3 C5
1 1 2 C2
2 A3 B1 C4
3 A4 2 3
4 A2 B3 C1
Upvotes: 4