【问题标题】:Pandas dataframe applying NA to part of the data将 NA 应用于部分数据的 Pandas 数据框
【发布时间】:2014-10-10 18:28:27
【问题描述】:

让我以我是使用 pandas 的新手作为开头,所以如果这个问题是基本的或以前回答过的,我很抱歉,我在网上查找并找不到我需要的东西。

我有一个包含棒球队日程的数据框。一些游戏已经玩过,因此游戏的结果被输入到数据框中。但是,对于尚未发生的游戏,只有要玩的时间(例如下午 1:35)。

所以,我想将所有尚未发生的游戏的值转换为 Na 的值。

谢谢

根据此处的要求,亚利桑那响尾蛇的结果数据框包含什么

print MLB['ARI']
0     0
1     0
2     0
3     1
4     0
5     0
6     0
7     0
8     1
9     0
10    1
...
151    3:40 pm
152    8:40 pm
153    8:10 pm
154    4:10 pm
155    4:10 pm
156    8:10 pm
157    8:10 pm
158    1:10 pm
159    9:40 pm
160    8:10 pm
161    4:10 pm
Name: ARI, Length: 162, dtype: object

【问题讨论】:

  • 你能发布一些示例记录吗?
  • @LiamFoley print MLB['ARI'] 0 0 1 0 2 0 3 1 4 0 5 0 6 0 7 0 8 1 9 0 10 1 11 1 12 0 13 0 14 0 ... 147 8:10 pm 148 4:10 pm 149 9:40 pm 150 9:40 pm 151 3:40 pm 152 8:40 pm 153 8:10 pm 154 4:10 pm 155 4:10 pm 156 8:10 pm 157 8:10 pm 158 1:10 pm 159 9:40 pm 160 8:10 pm 161 4:10 pm 名称:ARI,长度:162,dtype:objecty,z))
  • 我如何正确发布格式,它不允许我使用输入
  • 每行代码需要缩进4个空格。

标签: python-2.7 pandas type-conversion


【解决方案1】:

想不出任何直接的解决方案,只能迭代

for i in xrange(len(MLB)):
    if 'pm' in MLB.['ARI'].iat[i] or 'am' in MLB.['ARI'].iat[i]:
        MLB.['ARI'].iat[i] = np.nan

如果您的实际值(1 和 0)也是字符串,这应该可以工作。如果它们是数字,请尝试:

for i in xrange(len(MLB)):
    if type(MLB.['ARI'].iat[i]) != type(1):
        MLB.['ARI'].iat[i] = np.nan

【讨论】:

  • 出现错误:文件“”,第 1 行 MLB['ARI'].contains('pm') = np.nan SyntaxError: can't分配给函数调用
  • MLB[MLB['ARI']].contains('pm') = np.nan
  • 您需要在contains 前面加上str 才能访问字符串方法,即df['result'].str.contains。此外,在比较系列/ndarray 时,您需要使用 | 而不是 or
  • 抱歉,之前无法测试。
  • @Inox 谢谢,它成功了。我唯一要说的是,您的语法略有错误,您需要删除 MLB 之间的句点的 2 个实例。['ARI']
【解决方案2】:

更惯用的方法是使用矢量化字符串方法。

http://pandas.pydata.org/pandas-docs/stable/basics.html#vectorized-string-methods

mask = MLB['ARI'].str.contains('pm') #create boolean array
MLB['ARI'][mask] = np.nan #the column names goes first

从中创建布尔数组,然后使用它来选择所需的数据。 确保列名位于掩码数组之前,否则您将处理数据的副本并且您的原始数据框不会得到更新。

MLB['ARI'][mask] #returns a view on MLB datafrmae, will be updated
MLB[mask]['ARI'] #returns a copy of MLB, wont be updated.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    • 2022-12-21
    • 1970-01-01
    • 2016-12-14
    相关资源
    最近更新 更多