python - 在 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)
解决方案
你只需要简化你的代码 - 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'])
注意事项:
同一系列中的混合值是可能的,但是性能应该会降低并且一些功能应该被破坏,所以要小心。
推荐阅读
- c++ - 为什么在平台 A 上编译的静态库不能在平台 B 上使用而没有警告?
- python - 分离数据框列
- jquery - 带有常规 Div 的 JQuery UI 对话框堆叠顺序
- python - 不规则斑点中的最大圆/椭圆数
- c# - 无法找到 .NET Core SDK
- google-sheets-api - 如何根据单元格变化告诉客户发票状态
- python - Python 无法加载 boost.python dll
- intel-mkl - 静态和动态集群 MKL 有什么区别?
- qt5 - 在 Qt 中,如何根据另一个模型的更改来更新模型的布局?
- reactjs - 访问状态时,WebStorm 自动完成功能不适用于 ReactJs