【问题标题】:Converting string to int in Pandas column在 Pandas 列中将字符串转换为 int
【发布时间】:2019-04-08 02:35:03
【问题描述】:

我有一个带有 US Congress biographical data 的 .csv,我将其读取为 Panda df:

df = pd.read_csv('congress100.csv', delimiter = ';', names = ['Name', 'Position', 'Party', 'State', 'Congress'], header = 0)

我的数据框如下所示:

0                   'ACKERMAN, Gary Leonard'        'Representative'    'Democrat'  'NY'  '100(1987-1988)'
1                  'ADAMS, Brockman (Brock)'               'Senator'    'Democrat'  'WA'  '100(1987-1988)'
2                   'AKAKA, Daniel Kahikina'        'Representative'    'Democrat'  'HI'  '100(1987-1988)'
3    'ALEXANDER, William Vollie (Bill), Jr.'        'Representative'    'Democrat'  'AR'  '100(1987-1988)'
4                  'ANDERSON, Glenn Malcolm'        'Representative'    'Democrat'  'CA'  '100(1987-1988)'
5                   'ANDREWS, Michael Allen'        'Representative'    'Democrat'  'TX'  '100(1987-1988)'
6                          'ANNUNZIO, Frank'        'Representative'    'Democrat'  'IL'  '100(1987-1988)'
7             'ANTHONY, Beryl Franklin, Jr.'        'Representative'    'Democrat'  'AR'  '100(1987-1988)'
8                  'APPLEGATE, Douglas Earl'        'Representative'    'Democrat'  'OH'  '100(1987-1988)'
9            'ARCHER, William Reynolds, Jr.'        'Representative'  'Republican'  'TX'  '100(1987-1988)'
10                    'ARMEY, Richard Keith'        'Representative'  'Republican'  'TX'  '100(1987-1988)'

我想将“Congress”列中的数据转换为整数。现在,我首先将其转换为更简单的字符串:

df['Congress'] = df['Congress'].str.replace(r'100\(1987-1988\)', '1987')

这是成功的。但是,我正在尝试将那个更简单的字符串转换为整数:

df['Congress'] = df['Congress'].pd.to_numeric(errors='ignore')

我收到一个错误:

AttributeError: 'Series' object has no attribute 'pd'

请帮我解决这个错误并简化我的代码。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您需要像这样拨打pd.numeric

    import pandas as pd
    
    df = pd.DataFrame(data=[str(i + 1980) for i in range(10)], columns=['Congress'])
    df['Congress'] = pd.to_numeric(df['Congress'], errors='ignore')
    print(df)
    

    上面的代码是一个玩具示例,你只需要改变你的行:

    df['Congress'] = df['Congress'].pd.to_numeric(errors='ignore')
    

    到:

    df['Congress'] = pd.to_numeric(df['Congress'], errors='ignore')
    

    【讨论】:

    • 这实际上是在替换我的整个数据框,而我只想更改“Congress”列中的值。
    • @CharlieGoldberg 你确定吗?我只是运行它,添加了一个虚拟列,并且虚拟列没有改变。
    • 当我在执行你建议的代码后打印我的新 df 时,我得到这个:Congress 0 1980 1 1981 2 1982 3 1983 4 1984 5 1985 6 1986 7 1987 8 1988 9 1989
    • 该代码仅作为示例,您需要跳过创建数据框的部分。更新了答案!
    • 我明白了!我是这方面的新手。感谢您的澄清。
    【解决方案2】:

    实现它的另一种方法。如果列中只有数字,它将起作用:-

     df['Congress'] = df['Congress'].astype(int)
    

    【讨论】:

      猜你喜欢
      • 2020-04-08
      • 2017-02-04
      • 2018-06-27
      • 1970-01-01
      • 2016-04-14
      • 2016-08-30
      • 2020-10-22
      • 2015-02-23
      相关资源
      最近更新 更多