首页 > 解决方案 > 在 pandas 数据框中定义具有不同类型的列

问题描述

我有一个Data Frame来自 excel ( pd.read_excel()) 的 (df),我需要定义一个具有不同类型的新列,例如:

df['new col'] = df['Date1']
df.loc[condition('Date1'), 'new col'] = 'string'

Wheredf['Date1']是一列日期,并condition('Date1')检查“Date1”是否在给定的值范围内,而string是否是固定文本。我的代码给出错误。如何定义我的新列?

在条件()函数让:

a = df4['Date2'] - pd.Timedelta(2, unit='d')
b = df4['Date2'] + pd.Timedelta(2, unit='d')

condition('Date1')= df['Date1'].between(a, b, inclusive=False)

标签: pythonpandastypescalculated-columns

解决方案


你只需要简化你的代码 - fromdf4['Date1'].between(a, b, inclusive=False)是返回的布尔系列,所以只需要传递给loc

a = df4['Date2'] - pd.Timedelta(2, unit='d')
b = df4['Date2'] + pd.Timedelta(2, unit='d')

mask = df4['Date1'].between(a, b, inclusive=False)

df4['new col'] = df4['Date1']
df4.loc[mask, 'new col'] = 'string'

更好的选择numpy.where

df4['new col'] = np.where(mask, 'string', df4['Date1'])

注意事项

同一系列中的混合值是可能的,但是性能应该会降低并且一些功能应该被破坏,所以要小心。


推荐阅读