【问题标题】:Extracting values from a dataframe column with dtype 'o'从具有 dtype 'o' 的数据框列中提取值
【发布时间】:2017-05-03 11:55:40
【问题描述】:

我是 Python Pandas 的新手。在我的数据框中有一个名为'helpful' 的列,它有一个dtype 'o'。列中的值类似于[2,5]。我需要提取 2 和 5 以便对它们执行操作。谁能建议我如何做到这一点?

【问题讨论】:

  • print (type(df['helpful'].iat[0])) 是什么?

标签: python python-3.x pandas dataframe


【解决方案1】:
import pandas as pd
df = pd.DataFrame({'helpful': {0: [2, 5], 1: [3, 6]}})
print(df)
Out[742]: 
  helpful
0  [2, 5]
1  [3, 6]

#access first row for column helpful
df.helpful.values[0]
Out[743]: [2, 5]

#access first element of first row for column helpful
df.helpful.values[0][0]
Out[744]: 2

【讨论】:

    【解决方案2】:

    试试:

    df = pd.DataFrame({'helpful': ['2,5','4,0','7,3']})
    
    for val in df.helpful.apply(lambda x: x.split(',')):
        print val[0]
        print val[1]
        print '_'*3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-28
      • 1970-01-01
      • 2020-07-13
      • 1970-01-01
      • 2017-01-20
      • 1970-01-01
      • 2021-08-05
      • 2012-11-05
      相关资源
      最近更新 更多