Add a new column when the below conditions are achieved.
- if "Action" comes before "Scence" ==> Assign value equal 1 (in a new column)
- if "Dialogue" comes before "Scence" ==> Assign value equal 2 (in a new column)
- if "Scence" comes before "Scence" ==> Assign value equal 3 (in a new column)
My code is as below:
for i in range(len(df)):
if df['Type'][i] == "Action" < df['Type'][i] == "Scene":
i.append(1)
CodePudding user response:
I'm going to assume you're using pandas. Normally you don't want to iterate over each row like the way you're doing. What you can do is create an intermediary column which is just all the values shifted up by 1
e.g. df['shifted_Type'] = df['Type'].shift(-1)
import pandas as pd
def foo(row):
if row['type'] == 'action' and row['shifted_type'] == 'scene':
return 1
else: # add other comparisons here
return 0
df = pd.DataFrame()
# setting up a sample df
df['type'] = ['scene', 'action', 'action', 'scene','action']
# creating new column of 'type' shifted backward by 1
df['shifted_type'] = df['type'].shift(-1)
# creating new column of result with the specified logic in foo applied
df['result'] = df.apply(foo, axis=2)
print(df)
OUTPUT:
type shifted_type result
0 scene action 0
1 action action 0
2 action scene 1
3 scene action 0
4 action NaN 0
CodePudding user response:
@ajoseps Thanks for your great effort.
Yes, I am using pandas but I don't want to shift type.
I am classifying my scenes into 3 categories: So if the word "Action" comes before "Scene" this type is labeled as 0 in a new column. And if the word "Dialogue" comes before "Scene" this type is labeled as 1 in the same new column.