Specifically, I'm looking for a way to iterate over a Dataframe, and add such a row in case a condition is met. The added row will have the same index as the row it was added to. Couldn't find relevant information.
Code and data for the purpose of this question:
a = {'a': [1,3,5,7], 'b': [2,4 ,6, 8], 'c': [3, 5,7,9]}
b = pandas.DataFrame(a)
b
Out[4]:
a b c
0 1 2 3
1 3 4 5
2 5 6 7
3 7 8 9
If for the sum of the digits in a row: sum_row % 4 = 0
, the program adds a row to that row that has the same index as the initial row. The added row is not divided into columns, but rather it consists of a single cell with a comment.
Desired resulting dataframe should look like that:
a b c
0 1 2 3
1 3 4 5
sum_row % 4 yields no remainder
2 5 6 7
3 7 8 9
sum_row % 4 yields no remainder
or
a b c
0 1 2 3
1 3 4 5
1 sum_row % 4 yields no remainder
2 5 6 7
3 7 8 9
3 sum_row % 4 yields no remainder
Thanks.
CodePudding user response:
this is my interpretation: He needs evaluate "mod 4" (% 4) in every row. This is my old school loop into DATAFRAME using iterrows. With this code you can create a new DF into Loop, or create a D column with % 4 result.
import pandas as pd
# Loop in DATAFRAME
a = {'a': [1,3,5,7], 'b': [2,4 ,6, 8], 'c': [3, 5,7,9]}
b = pd.DataFrame(a)
# Print Data Frame
# print (b)
for index, x in b.iterrows():
# Print Line
print (x['a'] , x['b'] , x['c'] )
result = (x['a'] x['b'] x['c'] ) % 4
if result == 0:
# Print Result
print ('sum_row % 4 yields no remainder')
CodePudding user response:
The desired output as shown is not possible. You can do something like this:
import pandas as pd
spam = {'a': [1,3,5,7], 'b': [2,4 ,6, 8], 'c': [3, 5,7,9]}
df = pd.DataFrame(spam)
df['remainder'] = (df.sum(axis=1) % 4).astype(bool)
df['comment'] = df.remainder.apply(lambda x: 'remainder' if x else 'no remainder')
print(df)
output
a b c remainder comment
0 1 2 3 True remainder
1 3 4 5 False no remainder
2 5 6 7 True remainder
3 7 8 9 False no remainder