If Column Contains String then enter value for that row
We can use grepl
to return a logical index by matching the 'D' in the 'A' column, and then with ifelse
, change the logical vector to 'yes' and 'no'
df$C <- ifelse(grepl("D", df$A), "yes", "no")
check if row value value is equal to column name and access the value of the column
Use DataFrame.melt
for alternative for lookup:
df1 = df.melt('colfromvaluestobepicked', ignore_index=False)
df['new']=df1.loc[df1['colfromvaluestobepicked'].str.strip("'") == df1['variable'],'value']
If statement that checking value in current row and column
If you want to check each row of the column to make after this some #code
:
for row in df.iterrows():
if t==row['A']:
#code
If you only want to know in which rows of df['A']
the value of the element is t:
df.loc[df['A']==t, 'A']
or
df['A'].astype(str).str.contains('t')
EDIT
Check if it works for you:
df.loc[df['A']=='red','Value1']=df['Value']
df.loc[df['A']!='red','Value2']=df['Value']
If a dataframe contains a value in a column, how to perform a calculation in another column? - Pandas/ Python
You could check if column "A" values are 123 or not and use mask
on "C" to replace values there:
df['C'] = df['C'].mask(df['A']==123, df['B']*0.0008)
Output:
A B C
0 123 1500 1.2
Check if row has particular value in R
We can change the select
subset of data to a logical matrix
with ==
, then apply the rowSums
on the matrix, and check if the row wise sum is greater than 0
library(dplyr)
...
rowSums(select(., starts_with('type')) ==1, na.rm = TRUE) > 0
In addition to the above, it can be done using if_any
...
if_any(starts_with('type'), ~. == 1)
Check if column contains (/,-,_, *or~) and split in another column - Pandas
Use Series.str.split
with list of possible separators and create new DataFrame:
import re
L = ['-','/','*','~','_','^', '.']
#some values like `^.` are escape
pat = '|'.join(re.escape(x) for x in L)
df = df['column_name'].str.split(pat, expand=True).add_prefix('num')
print (df)
num0 num1 num2
0 152 6 3
1 163 1 6
2 145 1 None
3 163 6 3
EDIT: If need match values before value use:
L = ["\-_",'\^|\*','~','/']
for val in L:
df[f'before {val}'] = df['column_name'].str.extract(rf'(\d+){[val]}')
#for last value not exist separator, so match $ for end of string
df['last'] = df['column_name'].str.extract(rf'(\d+)$')
print (df)
column_name before \-_ before \^|\* before ~ before / last
0 152/2~3_4*5 3 4 2 152 5
1 152/2~3-4^5 4 4 2 152 5
2 152/6*3 NaN 6 NaN 152 3
3 163/1-6 NaN NaN NaN 163 6
4 145/1 NaN NaN NaN 145 1
5 163/6^3 6 6 NaN 163 3
Check if columns have a nan value if certain column has a specific value in Dataframe
so you have an if-elif-else situation. Then we can use np.select
for it. It needs the conditions and what to do when they are satisfied:
- your if is: "condition is 1 and a,b,c has all nan"
- your elif is: "condition is nan"
- what remains is else, as usual
conditions = [df.condition.eq(1) & df[["a", "b", "c"]].isna().all(axis=1),
df.condition.isna()]
what_to_do = ["O", "-"]
else_case = "X"
df["check_result"] = np.select(conditions, what_to_do, default=else_case)
df
condition a b c check_result
0 1.0 NaN NaN 3.0 X
1 NaN 4.0 2 2.0 -
2 NaN 5.0 e 1.0 -
3 NaN 6.0 2 2.0 -
4 1.0 NaN NaN NaN O
So we don't write else's condition. It goes to default.
Related Topics
Inserting Date Value into Date Field Using Laravel
Selecting Same Column Twice from a Single Table But With Different Conditions
Compare 2 Column Values in Same Table
How to Find the Row Count for All Your Tables in Postgres
Error 1067 (42000): Invalid Default Value for 'Created_At'
Pg_Restore: [Archiver] Unsupported Version (1.14) in File Header
How to Connect MySQL Workbench to Running MySQL Inside Docker
How to Convert Nvarchar to Numeric in SQL Server
Comparing Two Count Results Using SQL
How to Count Number of Digits After a Decimal Place
Oracle SQL Hours Difference Between Dates in Hh:Mm:Ss
Simple Check for Select Query Empty Result
Duplicate Rows When Joining Tables
How to Get Total Count Value Each Day Upto 5 Days
Joining Tables from Different Servers
Remove Blank Line in Between Select Queries When Spooling to CSV File
Extract String Part Between Single Quotes from Formula'S Divisor