Python simply wants to map data in DataFrame. Create M and N DataFrame, respectively, as shown below
import pandas as pd
M = { 'x': ['a', 'b', 'c'], 'y': ['1', '2', '3'] }
N = { 'i': ['3', '1', '2'] }
M = pd.DataFrame(M)
N = pd.DataFrame(N)
I want to find a value equal to a specific value in column i of N in column y of M, and then find the corresponding value (in the same row) in column x of M. For example, since M['y'][1] has the same value as the N['i'][2'] value ('b') in M['y'][1], you find the corresponding value in the x column, M['x'][1] value ('b'), and individually you could get the value of 'b' by typing as below.
M['x'][N['i'][2]==M['y']]
By the way, I want to process it collectively and store it in column j of N, but when I wrote it as below, the value of column j is displayed as [NaN, a, Nan]. What you want to see is [c, a, b].
N['j'] = ''
N['j'] = N.apply(lambda e: M['x'][e['i'] == M['y']], axis=1)
Finally, the purpose is to store the following values in the j column of N.
Please help me with how to modify it to work properly.
python pandas
import pandas as pd
M = { 'x': ['a', 'b', 'c'], 'y': ['1', '2', '3'] }
N = { 'i': ['3', '1', '2'] }
M = pd.DataFrame(M)
N = pd.DataFrame(N)
import string
mappedData = dict(zip(map(str, range(1, 27)), string.ascii_lowercase)) # '1':'a' '2':'b' ... '26':'z'
N['j'] = [mappedData[k] for k in N['i']]
N
Out[20]:
i j
0 3 c
1 1 a
2 2 b
If it's 1, then a 3, then c, so you can make a dictionary that uses numbers as a key as alphabets and figure out the value using that dictionary.
import pandas as pd
M = { 'x': ['a', 'b', 'c'], 'y': ['1', '2', '3'] }
N = { 'i': ['3', '1', '2'] }
M = pd.DataFrame(M)
N = pd.DataFrame(N)
mappedData = dict(zip(M['y'], M['x']))
N['j'] = N['i'].map(mappedData)
The results are the same. Once again, thank you for your help!
© 2024 OneMinuteCode. All rights reserved.