【问题标题】:Pandas str.split() function is not working properlyPandas str.split() 函数无法正常工作
【发布时间】:2019-11-08 21:24:07
【问题描述】:

在尝试使用 Pandas 系列 str.split() 函数拆分数据框“Actors”列中的值时,我得到的值比我指定的拆分多:

df['Actors'] = df['Actors'].str.split(",",n=3)

1      [timrobbins, morganfreeman, bobgunton, william...
2      [marlonbrando, alpacino, jamescaan, richardsca...
3      [alpacino, robertduvall, dianekeaton, robertde...
4      [christianbale, heathledger, aaroneckhart, mic...
5      [martinbalsam, johnfiedler, leejcobb, egmarshall]

如果我尝试使用下面的 sn-p 对上述结果进行切片,则 NaN 开始出现在结果中:

df['Actors'] = df['Actors'].str.split(",",n=3)[:3]
df['Actors'].head()

1    [timrobbins, morganfreeman, bobgunton, william...
2    [marlonbrando, alpacino, jamescaan, richardsca...
3    [alpacino, robertduvall, dianekeaton, robertde...
4                                                  NaN
5                                                  NaN
Name: Actors, dtype: object

或者,如果我使用如下所示的 apply 函数尝试 sn-p,则可以得到正确的结果:

df['Actors'] = df['Actors'].apply(lambda x: x.split(",")[:3])
df['Actors'].head()

1        [timrobbins, morganfreeman, bobgunton]
2           [marlonbrando, alpacino, jamescaan]
3         [alpacino, robertduvall, dianekeaton]
4    [christianbale, heathledger, aaroneckhart]
5         [martinbalsam, johnfiedler, leejcobb]
Name: Actors, dtype: object

我想知道为什么会发生这种异常以及在这种情况下如何正确使用 str.split() 函数?

要进一步检查数据,您可以使用以下 sn-p 代码自行下载数据:

df = pd.read_csv('https://query.data.world/s/uikepcpffyo2nhig52xxeevdialfl7',index_col=0)

【问题讨论】:

  • 您获得的价值不会超过您指定的值。这很难说,因为逗号是值之间的分隔符,也是原始数据中的分隔符,它不会在字符串周围显示引号。你会收到["timrobbins", "morganfreeman", "bobgunton, william..."]
  • 请尝试使用以下行在您的 jupyter notebook 或 i-python shell 中下载数据一次: df = pd.read_csv('query.data.world/s/…) df['Actors'] = df[ '演员'].str.strip().str.lower().str.replace("[^a-zA-Z,]","") df['演员'] = df['演员']。 str.split(", ",n=3) df['Actors'].head() 。这将使您更好地了解数据
  • 我不使用 jupyter 或 i-python。
  • 您有任何可用的示例数据吗?
  • 重点是n=3 并不意味着在第三项之后丢弃所有内容。这意味着它们都包含在第三个值中。

标签: python pandas dataframe split


【解决方案1】:

IIUC,你现在想知道str.split(",",n=3)[:3]str.split(",").str[:3] 有什么不同

str.split(",",n=3)[:3]',' 上从左到右拆分并拆分 3 次。拆分的输出是每行是一个列表的系列。接下来,在输出上调用[:3]。它对输出的前 3 行进行切片,并仅返回新的 3 行系列。

df['Actors'] = df['Actors'].str.split(",",n=3)[:3] 是系列赋值。系列分配在索引上对齐。输出 3 行系列中不存在的任何 df['Actors'].index 将在值中分配为 NaN。这就是最终 df['Actors'] 只有 3 行有值而其余的是 NaN

的原因

df['Actors'].str.split(",").str[:3],是熊猫Indexing with .str。即,它是 pandas str 访问器的内置功能。它通过传递给[] 的数字对每一行的整个系列进行切片。您可以在这里阅读更多内容:https://pandas.pydata.org/pandas-docs/stable/user_guide/text.html#indexing-with-str。它返回与原始序列相同长度(相同行数)的序列,其中每行值都被[] 中的数字分割。

【讨论】:

    【解决方案2】:

    我刚刚找到了完成这项工作的方法。到目前为止,我对此没有任何解释。也许你们可以帮助我解释部分,但这个 sn-p 确实有效:

    df['Actors'] = df['Actors'].str.split(",").str[:3]
    df['Actors'].head()
    
    1        [timrobbins, morganfreeman, bobgunton]
    2        [marlonbrando, alpacino, jamescaan]
    3        [alpacino, robertduvall, dianekeaton]
    4        [christianbale, heathledger, aaroneckhart]
    5        [martinbalsam, johnfiedler, leejcobb]
    Name: Actors, dtype: object
    

    【讨论】:

    • @jorijnsmit 非常感谢您的帮助
    • 有什么难以解释的?您拆分演员字符串,然后使用切片来获取前 3 个,这就是您想要的。
    • 您可以使用n=4,这样就不会浪费时间拆分您不感兴趣的剩余名称。
    • 好吧,让我告诉你什么很难得到:str.split(",",3) 这会返回什么?也许是一个清单???那么在那个列表上,你怎么能应用 .str 访问器,然后 slice[0:3] 是我的问题?
    • 它不返回列表。这些东西都是熊猫系列的。
    【解决方案3】:

    您对df['Actors'] = df['Actors'].str.split(",", n=3)[:3] 所做的不是对字符串进行切片,而是对Series 进行切片。这就是为什么您从第四行开始得到NaNs 的原因。用 [:2] 再试一次,你会从第三行得到NaNs。

    使用.apply(lambda x: x[:n]),您可以对实际的单个字符串进行切片。

    或者,如果您不想使用.apply(),您可以将每一行的内容 切片而不是系列本身:

    df['Actors'] = df['Actors'].str.split(",").str[:3]
    

    【讨论】:

    • 你提到的上面的sn-p不是正确的方法,我只是在玩了一下sn-p。实际的 sn-p : df['Actors'] = df['Actors'].str.split(",",n=3) 应该将 'Actors' 列中的字符串拆分为具有 3 个字符串元素的列表但这并没有发生。你能帮我解决一下吗?
    • 无意中找到了答案。请帮我解释一下。
    猜你喜欢
    • 1970-01-01
    • 2021-04-19
    • 2020-10-11
    • 1970-01-01
    • 2023-02-13
    • 2017-12-15
    • 2013-03-27
    • 2012-08-15
    • 2013-11-05
    相关资源
    最近更新 更多