【问题标题】:Single quote replacement, handling of null integers in pandas/python2.7单引号替换,pandas/python2.7中空整数的处理
【发布时间】:2013-06-23 22:25:30
【问题描述】:

Pandas/Python 新手,我不得不编写一些笨拙的代码。我将不胜感激您将如何执行此操作并加快速度(我将针对千兆字节的数据执行此操作)。

所以,我正在使用 pandas/python 进行一些 ETL 工作。执行逐行计算,因此我需要它们作为流程中的数字类型(这部分省略)。我需要将一些字段作为数组输出,并去掉单引号、nan 和“.0”。

第一个问题,有没有办法在 R 中对这些 if else 语句 ala ifelse 进行矢量化?其次,肯定有更好的方法来删除“.0”。 pandas/numpy 处理数字类型中的空值似乎存在重大问题。

最后,.replace 似乎不适用于单引号的 DataFrame。我错过了什么吗?这是示例代码,如果您对此有任何疑问,请告诉我:

import pandas as pd

# have some nulls and need it in integers
d = {'one' : [1.0, 2.0, 3.0, 4.0],'two' : [4.0, 3.0, NaN, 1.0]}
dat = pd.DataFrame(d)

# make functions to get rid of the ".0" and necessarily converting to strings
def removeforval(val):
    if str(val)[-2:] == ".0":
        val = str(val)[:len(str(val))-2]
    else:
        val = str(val)
    return val
def removeforcol(col):
    col = col.apply(removeforval)
    return col
dat = dat.apply(removeforcol,axis=0)
# remove the nan's
dat = dat.replace('nan','')

# need some fields in arrays on a postgres database
quoted  = ['{' + str(tuple(x))[1:-1] + '}'  for x in dat.to_records(index=False)]
print "Before single quote removal"
print quoted

# try to replace single quotes using DataFrame's replace
quoted_df = pd.DataFrame(quoted).replace('\'','')
quoted_df = quoted_df.replace('\'','')
print "DataFrame does not seem to work"
print quoted_df

# use a loop
for item in range(len(quoted)):
    quoted[item] = quoted[item].replace('\'','')
print "This Works"
print quoted

谢谢!

【问题讨论】:

  • 你能展示你想要的输出吗?
  • [{4,1},{2,3},{3,},{4,1}] 就像最后一个输出一样
  • 我误会它是这样的列表 ['{1, 4}', '{2, 3}', '{3, }', '{4, 1}']
  • 好吧,{ 也很奇怪,那是字典(而不是元组引用)

标签: python-2.7 replace pandas nan


【解决方案1】:

你明白,这样制作一个字符串是很奇怪的。这根本不是有效的python。你在用这个做什么?你为什么要把它串起来?

修改

In [144]: list([ "{%s , %s}" % tup[1:] for tup in df.replace(np.nan,0).astype(int).replace(0,'').itertuples() ])
Out[144]: ['{1 , 4}', '{2 , 3}', '{3 , }', '{4 , 1}']

【讨论】:

  • 我对 Python 的信心恢复了。 2 轻微偏差。我实际上不知道脚本运行之前有多少列。我只会将所需的字符串输入到您的代码中。此外,我在整个 DataFrame 中还有许多其他字段。现在,我正在从由其他逻辑确定的列名列表中进行子设置。我仍然想知道是否有办法向量化该逻辑。即,如果 list 中的 columnname 则执行此操作,否则执行此操作,而无需该构造。这样做的重点是通过 psql COPY 保存和加载到 postgres,这是 SQL 数组的格式。
  • 你最好只使用df.to_sql()(在即将发布的 0.12 中重命名),请参见此处:pandas.pydata.org/pandas-docs/dev/io.html#sql-queries
猜你喜欢
  • 2019-04-02
  • 2021-08-17
  • 2020-01-27
  • 2021-05-16
  • 1970-01-01
  • 2018-07-17
  • 2018-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多