Python2.7按行设置列的pandas条件

2024-06-06 21:11:33 发布

您现在位置:Python中文网/ 问答频道 /正文

(我不擅长给这些问题起标题…)

因此,我已经完成了90%的熊猫学习过程,但我还有一件事要做。我来举个例子(实际的原始文件是一个逗号分隔的CSV,它有更多的行):

 Name    Price    Rating    URL                Notes1       Notes2            Notes3
 Foo     $450     9         a.com/x            NaN          NaN               NaN
 Bar     $99      5         see over           www.b.com    Hilarious         Nifty
 John    $551     2         www.c.com          Pretty       NaN               NaN
 Jane    $999     8         See Over in Notes  Funky        http://www.d.com  Groovy

URL列可以表示许多不同的内容,但它们都包含“see over”,并且不一致地指出右侧的哪一列包含站点。在

我想在这里做几件事:首先,将网站从任何Notes列移到URL;其次,将所有Notes列折叠为一列,并在它们之间添加一行新行。为了让我用熊猫的航向位置)公司名称:

^{pr2}$

我做了这样一件事:

 df['URL'] = df['URL'].fillna('')
 df['Notes1'] = df['Notes1'].fillna('')
 df['Notes2'] = df['Notes2'].fillna('')
 df['Notes3'] = df['Notes3'].fillna('')
 to_move = df['URL'].str.lower().str.contains('see over')
 df.loc[to_move, 'URL'] = df['Notes1']

我不知道如何在www或.com上找到Notes列。例如,如果我的条件是我的条件,例如:

 if df['Notes1'].str.lower().str.contains('www'):
    df.loc[to_move, 'URL'] = df['Notes1']

我回到了ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all(),但是添加.any()或{}有一个明显的缺陷,那就是它们没有给出我要找的东西:对于任何一个,例如,URL中满足tomove要求的每一行都将得到Notes1中的内容。我需要逐行检查。出于类似的原因,我甚至无法开始折叠Notes列(而且我也不知道如何检查非空的空字符串单元格,这是我在这里创建的一个问题)。在

我知道,当第一个条件满足时,我还必须将Notes2移到Notes1,Notes3到Notes2,并将“”移到Notes3,因为我不希望在Notes列中使用剩余的url。我相信熊猫的路线比我现在做的要简单,因为它是熊猫,当我试着用熊猫做任何事情时,我发现它可以在一条线上完成,而不是我的20条。。。在

(请注意,我不在乎Notes2和Notes3这两个空列是否还剩下,b/c下一步我不会在CSV导入中使用它们,尽管我总能学到更多我需要的东西)

更新:所以我一步一步地使用我的非pandas python逻辑找到了一个糟糕的冗长的解决方案。我想到了这个(同样的前五行,减去航向位置线路):

url_in1 = df['Notes1'].str.contains('\.com')
url_in2 = df['Notes2'].str.contains('\.com')
to_move = df['URL'].str.lower().str.contains('see-over')
to_move1 = to_move & url_in1 
to_move2 = to_move & url_in2
df.loc[to_move1, 'URL'] = df.loc[url_in1, 'Notes1']
df.loc[url_in1, 'Notes1'] = df['Notes2']
df.loc[url_in1, 'Notes2'] = ''
df.loc[to_move2, 'URL'] = df.loc[url_in2, 'Notes2']
df.loc[url_in2, 'Notes2'] = ''

(在实际代码中移动行并重复移动)我知道必须有一个更有效的方法。。。这也不会在Notes列中崩溃,但是使用相同的方法应该很容易,只是我仍然不知道找到空字符串的好方法。在


Tags: tocomurldfmovewwwnanloc
1条回答
网友
1楼 · 发布于 2024-06-06 21:11:33

我还在学习pandas,所以这段代码的某些部分可能不那么优雅,但总体思想是-获取所有notes列,找到其中的所有url,将其与URL列合并,然后将剩余的notes合并到Notes1列中:

import pandas as pd
import numpy as np
import pandas.core.strings as strings

# Just to get first notnull occurence
def geturl(s):
    try:
        return next(e for e in s if not pd.isnull(e))
    except:
        return np.NaN

df =  pd.read_csv("d:/temp/data2.txt")

dfnotes = df[[e for e in df.columns if 'Notes' in e]]

#       Notes1            Notes2  Notes3
# 0        NaN               NaN     NaN
# 1  www.b.com         Hilarious   Nifty
# 2     Pretty               NaN     NaN
# 3      Funky  http://www.d.com  Groovy

dfurls = dfnotes.apply(lambda x: x.str.contains('\.com'), axis=1)
dfurls = dfurls.fillna(False).astype(bool)

#   Notes1 Notes2 Notes3
# 0  False  False  False
# 1   True  False  False
# 2  False  False  False
# 3  False   True  False

turl = dfnotes[dfurls].apply(geturl, axis=1)

df['URL'] = np.where(turl.isnull(), df['URL'], turl)
df['Notes1'] = dfnotes[~dfurls].apply(lambda x: strings.str_cat(x[~x.isnull()], sep=' '), axis=1)

del df['Notes2']
del df['Notes3']

df
#    Name Price  Rating               URL           Notes1
# 0   Foo  $450       9           a.com/x                 
# 1   Bar   $99       5         www.b.com  Hilarious Nifty
# 2  John  $551       2         www.c.com           Pretty
# 3  Jane  $999       8  http://www.d.com     Funky Groovy

相关问题 更多 >