Python: create new column and copy value from other row which is a swap of current row
I have a dataframe which has 3 columns:
import pandas as pd
d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]
df = pd.DataFrame(d)
Dataframe looks like this:
A B VALUE
left right 0
right left 1
east west 2
west east 3
south north 4
north south 5
I am trying to create a new column VALUE_2 which should contain the value from the swapped row in the same Dataframe.
Eg: right - left value is 0, left - right value is 1 and I want the swapped values in the new column like this:
A B VALUE VALUE_2
left right 0 1
right left 1 0
east west 2 3
west east 3 2
south north 4 5
north south 5 4
I tried:
for row_num, record in df.iterrows():
A = df['A'][index]
B = df['B'][index]
if(pd.Series([record['A'] == B, record['B'] == A).all()):
df['VALUE_2'] = df['VALUE']
I'm struck here, inputs will be highly appreciated.
python-3.x pandas
add a comment |
I have a dataframe which has 3 columns:
import pandas as pd
d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]
df = pd.DataFrame(d)
Dataframe looks like this:
A B VALUE
left right 0
right left 1
east west 2
west east 3
south north 4
north south 5
I am trying to create a new column VALUE_2 which should contain the value from the swapped row in the same Dataframe.
Eg: right - left value is 0, left - right value is 1 and I want the swapped values in the new column like this:
A B VALUE VALUE_2
left right 0 1
right left 1 0
east west 2 3
west east 3 2
south north 4 5
north south 5 4
I tried:
for row_num, record in df.iterrows():
A = df['A'][index]
B = df['B'][index]
if(pd.Series([record['A'] == B, record['B'] == A).all()):
df['VALUE_2'] = df['VALUE']
I'm struck here, inputs will be highly appreciated.
python-3.x pandas
add a comment |
I have a dataframe which has 3 columns:
import pandas as pd
d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]
df = pd.DataFrame(d)
Dataframe looks like this:
A B VALUE
left right 0
right left 1
east west 2
west east 3
south north 4
north south 5
I am trying to create a new column VALUE_2 which should contain the value from the swapped row in the same Dataframe.
Eg: right - left value is 0, left - right value is 1 and I want the swapped values in the new column like this:
A B VALUE VALUE_2
left right 0 1
right left 1 0
east west 2 3
west east 3 2
south north 4 5
north south 5 4
I tried:
for row_num, record in df.iterrows():
A = df['A'][index]
B = df['B'][index]
if(pd.Series([record['A'] == B, record['B'] == A).all()):
df['VALUE_2'] = df['VALUE']
I'm struck here, inputs will be highly appreciated.
python-3.x pandas
I have a dataframe which has 3 columns:
import pandas as pd
d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]
df = pd.DataFrame(d)
Dataframe looks like this:
A B VALUE
left right 0
right left 1
east west 2
west east 3
south north 4
north south 5
I am trying to create a new column VALUE_2 which should contain the value from the swapped row in the same Dataframe.
Eg: right - left value is 0, left - right value is 1 and I want the swapped values in the new column like this:
A B VALUE VALUE_2
left right 0 1
right left 1 0
east west 2 3
west east 3 2
south north 4 5
north south 5 4
I tried:
for row_num, record in df.iterrows():
A = df['A'][index]
B = df['B'][index]
if(pd.Series([record['A'] == B, record['B'] == A).all()):
df['VALUE_2'] = df['VALUE']
I'm struck here, inputs will be highly appreciated.
python-3.x pandas
python-3.x pandas
asked Nov 15 '18 at 7:10
PokemonPokemon
205
205
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
Use map by Series:
df['VALUE_2'] = df['A'].map(df.set_index('B')['VALUE'])
print (df)
A B VALUE VALUE_2
0 left right 0 1
1 right left 1 0
2 east west 2 3
3 west east 3 2
4 south north 4 5
5 north south 5 4
Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.
– Pokemon
Nov 15 '18 at 7:39
@Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?
– jezrael
Nov 15 '18 at 7:40
Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.
– Pokemon
Nov 15 '18 at 7:52
1
so need swap each value for each 2 rows groups? likedf['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values?
– jezrael
Nov 15 '18 at 8:14
1
This looks perfect! ;)
– Pokemon
Nov 15 '18 at 9:50
|
show 2 more comments
Just a more verbose answer:
import pandas as pd
d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]
df = pd.DataFrame(d)
pdf = pd.DataFrame()
for idx, item in df.iterrows():
indx = list(df['B']).index(str(df['A'][idx]))
pdf = pdf.append(pd.DataFrame('VALUE_2': df.iloc[indx][2], index=[0]), ignore_index=True)
print(pdf)
data = pd.concat([df, pdf], axis=1)
print(data)
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53314127%2fpython-create-new-column-and-copy-value-from-other-row-which-is-a-swap-of-curre%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
2 Answers
2
active
oldest
votes
2 Answers
2
active
oldest
votes
active
oldest
votes
active
oldest
votes
Use map by Series:
df['VALUE_2'] = df['A'].map(df.set_index('B')['VALUE'])
print (df)
A B VALUE VALUE_2
0 left right 0 1
1 right left 1 0
2 east west 2 3
3 west east 3 2
4 south north 4 5
5 north south 5 4
Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.
– Pokemon
Nov 15 '18 at 7:39
@Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?
– jezrael
Nov 15 '18 at 7:40
Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.
– Pokemon
Nov 15 '18 at 7:52
1
so need swap each value for each 2 rows groups? likedf['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values?
– jezrael
Nov 15 '18 at 8:14
1
This looks perfect! ;)
– Pokemon
Nov 15 '18 at 9:50
|
show 2 more comments
Use map by Series:
df['VALUE_2'] = df['A'].map(df.set_index('B')['VALUE'])
print (df)
A B VALUE VALUE_2
0 left right 0 1
1 right left 1 0
2 east west 2 3
3 west east 3 2
4 south north 4 5
5 north south 5 4
Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.
– Pokemon
Nov 15 '18 at 7:39
@Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?
– jezrael
Nov 15 '18 at 7:40
Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.
– Pokemon
Nov 15 '18 at 7:52
1
so need swap each value for each 2 rows groups? likedf['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values?
– jezrael
Nov 15 '18 at 8:14
1
This looks perfect! ;)
– Pokemon
Nov 15 '18 at 9:50
|
show 2 more comments
Use map by Series:
df['VALUE_2'] = df['A'].map(df.set_index('B')['VALUE'])
print (df)
A B VALUE VALUE_2
0 left right 0 1
1 right left 1 0
2 east west 2 3
3 west east 3 2
4 south north 4 5
5 north south 5 4
Use map by Series:
df['VALUE_2'] = df['A'].map(df.set_index('B')['VALUE'])
print (df)
A B VALUE VALUE_2
0 left right 0 1
1 right left 1 0
2 east west 2 3
3 west east 3 2
4 south north 4 5
5 north south 5 4
answered Nov 15 '18 at 7:13
jezraeljezrael
345k25300371
345k25300371
Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.
– Pokemon
Nov 15 '18 at 7:39
@Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?
– jezrael
Nov 15 '18 at 7:40
Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.
– Pokemon
Nov 15 '18 at 7:52
1
so need swap each value for each 2 rows groups? likedf['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values?
– jezrael
Nov 15 '18 at 8:14
1
This looks perfect! ;)
– Pokemon
Nov 15 '18 at 9:50
|
show 2 more comments
Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.
– Pokemon
Nov 15 '18 at 7:39
@Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?
– jezrael
Nov 15 '18 at 7:40
Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.
– Pokemon
Nov 15 '18 at 7:52
1
so need swap each value for each 2 rows groups? likedf['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values?
– jezrael
Nov 15 '18 at 8:14
1
This looks perfect! ;)
– Pokemon
Nov 15 '18 at 9:50
Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.
– Pokemon
Nov 15 '18 at 7:39
Great, works well. If I have 4 columns A, B, C, D with the same condition of swap (A,B & C,D), how do I go about that? Hint please.
– Pokemon
Nov 15 '18 at 7:39
@Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?
– jezrael
Nov 15 '18 at 7:40
@Pokemon - do you think pairs of columns? Can you add some date sample, 3-4 rows?
– jezrael
Nov 15 '18 at 7:40
Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.
– Pokemon
Nov 15 '18 at 7:52
Yes, for example A, B, C, D, VALUE are columns, 1st row is: (x, y, z, p, 100), 2nd row: (z, p, x, y, 50), 3rd row: (a, b, x, y, 200), 4th row: (x, y, a, b, 150) and so on. So, at any given point in time, only the column pairs A, B and C, D are swapped in the rows.
– Pokemon
Nov 15 '18 at 7:52
1
1
so need swap each value for each 2 rows groups? like
df['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values ?– jezrael
Nov 15 '18 at 8:14
so need swap each value for each 2 rows groups? like
df['new'] = df.groupby(df.index // 2)['VALUE'].agg([('a','last'),('b','first')]).stack().values ?– jezrael
Nov 15 '18 at 8:14
1
1
This looks perfect! ;)
– Pokemon
Nov 15 '18 at 9:50
This looks perfect! ;)
– Pokemon
Nov 15 '18 at 9:50
|
show 2 more comments
Just a more verbose answer:
import pandas as pd
d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]
df = pd.DataFrame(d)
pdf = pd.DataFrame()
for idx, item in df.iterrows():
indx = list(df['B']).index(str(df['A'][idx]))
pdf = pdf.append(pd.DataFrame('VALUE_2': df.iloc[indx][2], index=[0]), ignore_index=True)
print(pdf)
data = pd.concat([df, pdf], axis=1)
print(data)
add a comment |
Just a more verbose answer:
import pandas as pd
d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]
df = pd.DataFrame(d)
pdf = pd.DataFrame()
for idx, item in df.iterrows():
indx = list(df['B']).index(str(df['A'][idx]))
pdf = pdf.append(pd.DataFrame('VALUE_2': df.iloc[indx][2], index=[0]), ignore_index=True)
print(pdf)
data = pd.concat([df, pdf], axis=1)
print(data)
add a comment |
Just a more verbose answer:
import pandas as pd
d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]
df = pd.DataFrame(d)
pdf = pd.DataFrame()
for idx, item in df.iterrows():
indx = list(df['B']).index(str(df['A'][idx]))
pdf = pdf.append(pd.DataFrame('VALUE_2': df.iloc[indx][2], index=[0]), ignore_index=True)
print(pdf)
data = pd.concat([df, pdf], axis=1)
print(data)
Just a more verbose answer:
import pandas as pd
d = 'A': ['left', 'right', 'east', 'west', 'south', 'north'], 'B': ['right', 'left', 'west', 'east', 'north', 'south'], 'VALUE': [0, 1, 2, 3, 4, 5]
df = pd.DataFrame(d)
pdf = pd.DataFrame()
for idx, item in df.iterrows():
indx = list(df['B']).index(str(df['A'][idx]))
pdf = pdf.append(pd.DataFrame('VALUE_2': df.iloc[indx][2], index=[0]), ignore_index=True)
print(pdf)
data = pd.concat([df, pdf], axis=1)
print(data)
answered Nov 15 '18 at 7:53
RussellBRussellB
8191330
8191330
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53314127%2fpython-create-new-column-and-copy-value-from-other-row-which-is-a-swap-of-curre%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown