【问题标题】:Pandas Data frame column condition check based on length of the value基于值长度的 Pandas Dataframe 列条件检查
【发布时间】:2021-07-27 20:53:03
【问题描述】:

我有通过读取 excel 文件创建的 pandas 数据框。 excel 文件有一列称为序列号。然后我将序列号传递给连接到 API 的另一个函数并为我获取这些序列号的结果集。

我的代码-:

def create_excel(filename):
try:
    data = pd.read_excel(filename, usecols=[4,18,19,20,26,27,28],converters={'Serial Number': '{:0>32}'.format})
except Exception as e:
    sys.exit("Error reading %s: %s" % (filename, e))

data["Subject Organization"].fillna("N/A",inplace= True)
df = data[data['Subject Organization'].str.contains("Fannie",case = False)]
#df['Serial Number'].apply(lamda x:  '000'+x  if  len(x) == 29 else  '00'+x if len(x) == 30 else '0'+x if len(x) == 31 else x)  
print(df)
df.to_excel(r'Data.xlsx',index= False)
output = df['Serial Number'].apply(lambda x: fetch_by_ser_no(x))
df2 = pd.DataFrame(output)
df2.columns = ['Output']
df5 = pd.concat([df,df2],axis = 1)

我面临的问题是我想检查 fetch_by_ser_no() 返回的 df5 是否为空白,然后通过添加两个前导 00 使序列号为 34 个字符,然后再次检查函数。

如何通过不创建多个数据框来做到这一点

任何帮助!

谢谢

【问题讨论】:

    标签: pandas


    【解决方案1】:

    你可以尝试使用if ... else ...:

     output = df['Serial Number'].apply(lambda x: 'ok' if fetch_by_ser_no(x) else 'badly')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-10
      • 2017-04-11
      • 2019-05-19
      • 2016-01-18
      • 1970-01-01
      • 1970-01-01
      • 2021-07-17
      相关资源
      最近更新 更多