python - 如何根据特定条件将数据框中具有月份的列转换为字母数字(非数字)

标签 python pandas

我有一个数据框,其中一列包含月份。

我想用字母数字更新月份的值(一、二、三等,而不是 1、2、3 等) 是否有任何库可用于对整个列进行此转换?

附言- 该列包含超过 1200 行,因此手动操作毫无意义。

最佳答案

没有图书馆会自动为您做这件事。您必须为每个月提供值,因为您提到您有月份“名称”而不是数字。试试这个:

df['arrival_date_month'] = df['arrival_date_month'].str[:3]
df.loc[df["arrival_date_month"] == "Jan", 'arrival_date_month'] = 'One'
df.loc[df["arrival_date_month"] == "Feb", 'arrival_date_month'] = 'Two'
df.loc[df["arrival_date_month"] == "Mar", 'arrival_date_month'] = 'Three'
df.loc[df["arrival_date_month"] == "Apr", 'arrival_date_month'] = 'Four'
df.loc[df["arrival_date_month"] == "May", 'arrival_date_month'] = 'Five'
df.loc[df["arrival_date_month"] == "Jun", 'arrival_date_month'] = 'Six'
df.loc[df["arrival_date_month"] == "Jul", 'arrival_date_month'] = 'Seven'
df.loc[df["arrival_date_month"] == "Aug", 'arrival_date_month'] = 'Eight'
df.loc[df["arrival_date_month"] == "Sep", 'arrival_date_month'] = 'Nine'
df.loc[df["arrival_date_month"] == "Oct", 'arrival_date_month'] = 'Ten'
df.loc[df["arrival_date_month"] == "Nov", 'arrival_date_month'] = 'Eleven'
df.loc[df["arrival_date_month"] == "Dec", 'arrival_date_month'] = 'Twelve'

有趣的事实:如果您想根据某些条件设置值,您也可以在这里使用条件。尝试用其他条件替换 == "Jan"。

干杯!

关于python - 如何根据特定条件将数据框中具有月份的列转换为字母数字(非数字),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60950352/

相关文章:

python - 如何根据 Python 中另一个数据框的关系为变量赋值

python - np.where 用字符串创建缺失值

python - 提取csv文件的多个多边形坐标

python - 清除pyqt中QWidget上的布局

python - mpi4py 返回排名差异

python - 安装 PyQt5 时出错 : const class QJsonValue’ has no member named ‘toInt’

python - pandas 函数根据匹配列填充其他数据框中的缺失值?

python - 将具有多个参数的函数应用于 pandas groupby 对象

python - pip geoip在ubuntu gcc中安装错误

python - 如果同一行中的 2 列具有 NAN 值,则删除 pandas 中的行