【问题标题】:Define function to convert string to integer in Python在 Python 中定义将字符串转换为整数的函数
【发布时间】:2017-12-03 03:07:34
【问题描述】:

这可能是一个非常简单的问题,但我将不胜感激!

作为更大脚本的一部分,我有一个包含两列“file_name”和“value”的数据框(从 csv 文件导入)。下面我有一个简短的例子:

            file_name  value
0  201623800811s.fits   True
1  201623802491s.fits   True
2  201623802451s.fits  False

我想定义一个函数来读取“value”列中的值,并为“False”返回 0,为“True”返回 1。然后我想将结果附加到数据框中的第三列,最后将更新的数据框导出到 csv。

我定义了一个我认为可以工作的函数。但是,当我运行脚本时它不会执行并且我收到消息:

<function convert_string at 0x000000000DE35588>

在控制台中。 我的功能如下。欢迎任何帮助或建议。

def convert_string(explosions):
    for i in range(0,len(explosions)):
        if i == 'True' :
            return 1
        elif i == 'False' :
            return 0
        else:
            return 2

print convert_string 

【问题讨论】:

  • 你永远不会调用你的函数。

标签: string python-2.7 function integer type-conversion


【解决方案1】:

如果您在处理数据帧时使用了显式的for 循环,那么您很可能“做错了”。另外,如果您在第一次迭代中return,那么使用for 循环有什么意义?

考虑这些:

import numpy as np

df['third_column'] = np.where(df['value'], 1, 0)

如果你坚持定义一个函数:

def foo(x):
    return int(x)

df['third_column'] = df['value'].apply(foo)

或者干脆

df['third_column'] = df['value'].apply(lambda x: int(x))

完整示例:

import pandas as pd
import numpy as np

df = pd.DataFrame({'value': [True, False]})
print(df)

#     value
#  0   True
#  1  False

df['third_column'] = np.where(df['value'], 1, 0) 
print(df)

#     value  third_column
#  0   True             1
#  1  False             0

【讨论】:

  • 谢谢,这是一组有用的替代方案,比我自己的代码写得更优雅。当您说对数据框显式使用 for 循环是“做错了”时,是因为您的数据框已经定义了您希望使用的数据吗?
【解决方案2】:

您没有调用该函数。您的打印语句应该是:print convert_string(&lt;value&gt;),其中&lt;value&gt; 是一个整数。

【讨论】:

    猜你喜欢
    • 2010-12-27
    • 2010-10-31
    • 1970-01-01
    • 2013-02-18
    • 1970-01-01
    • 2022-08-12
    • 2013-06-03
    • 2015-09-25
    相关资源
    最近更新 更多