我有一个95列的数据帧,从第4列开始,我想将第4列与第5列进行比较,将结果作为第6列和第7列和第8列插入,并在第8列插入数据,直到循环结束。如何在熊猫身上做到这一点?
Ex of manual compare.
df['col_compare'] = np.where(df['payment_dt'] == df['payment_dt_x'], 'no change', 'changed')发布于 2021-05-25 12:34:47
尝试以下代码:
import pandas as pd
import random
import numpy as np
df = pd.DataFrame()
for i in range(1, 10): # fill the DataFrame
df['Column' + str(i)] = [random.randint(1, 2) for x in range(0, 10)]
for i in range(0, len(df.columns) - 2, 3):
df.iloc[:, i + 2] = np.where(df.iloc[:, i] == df.iloc[:, i + 1], 'no change', 'changed')
print(df)输出:
Column1 Column2 Column3 Column4 ... Column6 Column7 Column8 Column9
0 2 2 no change 1 ... no change 1 1 no change
1 1 2 changed 2 ... no change 2 1 changed
2 1 2 changed 1 ... no change 1 1 no change
3 2 2 no change 2 ... changed 1 1 no change
4 1 1 no change 2 ... changed 2 2 no change
5 2 1 changed 2 ... no change 2 2 no change
6 2 1 changed 2 ... no change 2 1 changed
7 2 2 no change 2 ... no change 1 1 no change
8 2 1 changed 1 ... changed 2 2 no change
9 2 2 no change 2 ... no change 1 1 no change
[10 rows x 9 columns]
Process finished with exit code 0https://stackoverflow.com/questions/67681509
复制相似问题