【问题标题】:Function that concatenates a string and a integer converts to float before converting to string连接字符串和整数的函数在转换为字符串之前转换为浮点数
【发布时间】:2019-08-30 05:50:36
【问题描述】:

我编写了一个 if-else 函数,它根据季度数将字符串(即“1/1/”)与转换为字符串的整数(即 str(2017))连接起来。我想在三个数据框上使用它。其中两个数据框产生了预期的结果(即“2017 年 1 月 1 日”)。最后一个数据框生成以下“1/1/2017.0”,这使其无法转换为日期时间。

我不知所措,因为根据 dtypes,所有三个数据帧都将季度和年份都列为 int64,并且所有三个数据帧最初都来自同一个 csv。

我的第一个猜测是,当我准备最后一个数据框时,我已经将我的年份转换为浮点数。我试图确保年份列是带有 .astype() 的整数。在应用函数之前和之后,年份列在 .dtypes 下作为 int64 列出。

数据框

from pandas import DataFrame

Data = {'quarter': [1,2,3,4],
         'year': [2017,2017,2017,2017]}
df = DataFrame(Data, columns = ['quarter', 'year'])

这是我正在使用的功能

def f(row):
    if row['quarter'] == 1:
        val = '1/1/' + str(row['year'])
    elif row['quarter'] == 2:
        val = '4/1/' + str(row['year'])
    elif row['quarter'] == 3:
        val = '7/1/' + str(row['year'])
    else:
        val = '10/1/' + str(row['year'])
    return val

我的预期结果是 '1/1/2017'、'4/1/2017'、'7/1/2017'、'10/1/2017'

我没有收到任何错误消息或警告。

【问题讨论】:

  • 它对我有用。这个for _, row in df.iterrows(): print(f(row)) 打印1/1/20174/1/20177/1/201710/1/2017(每个都在一个单独的行中)。
  • 我的主要问题是它在另外两个数据帧上的工作方式完全符合预期。我无法理解为什么完全相同的条件会在第三次产生不同的结果
  • 那么你可能应该在你的问题中发布第三个数据框,那个不起作用。
  • df 的年列中是否有 null/NaN 行不起作用?

标签: python pandas


【解决方案1】:

不确定为什么您的代码不适用于第三个数据集,但您可以使用 pandas 的函数而不是自己编写。它可能会解决您的问题。

>>> df['date'] = pd.to_datetime(
...     df['year'].astype(str).str.cat(df['quarter'].astype(str), sep='Q'))
>>> df
   quarter  year       date
0        1  2017 2017-01-01
1        2  2017 2017-04-01
2        3  2017 2017-07-01
3        4  2017 2017-10-01

您可以更改日期格式,例如:

>>> df['date'].dt.strftime('%m/%d/%Y')
0    01/01/2017
1    04/01/2017
2    07/01/2017
3    10/01/2017
Name: date, dtype: object

【讨论】:

    猜你喜欢
    • 2011-11-25
    • 1970-01-01
    • 2016-05-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    相关资源
    最近更新 更多