2021-03-26

pandas怎么新增一列,存入指定两列中的较小值?

l = [[9,2,3],[4,5,6],[8,7,1]]
d=DataFrame(l, columns=['a','b','c'])
希望d新增一列,该列为d中a和c列的较小值。即结果为:
d['d']=[3,4,1],请问该怎么简洁的实现呢?

代码块

import pandas as pd
import numpy as np


'''
pandas怎么新增一列,存入指定两列中的较小值?
'''


l = [[9,2,3],[4,5,6],[8,7,1]]

df=pd.DataFrame(l, columns=['a','b','c'])
print(df)
def cal1(x_df):
    return min(x_df['a'],x_df['c'])

res=df.apply(cal1,axis=1)
df['d']=res
print(df)

代码结果:

PS D:\pcharm> & C:/Users/jiaoshi01/AppData/Local/Programs/Python/Python36-32/python.exe d:/pcharm/1.py
a b c
0 9 2 3
1 4 5 6
2 8 7 1
a b c d
0 9 2 3 3
1 4 5 6 4
2 8 7 1 1
PS D:\pcharm>

你可能感兴趣的:(2021-03-26)