【问题标题】:Pandas: If substring is in string, return value of adjacent cellPandas:如果子字符串在字符串中,则返回相邻单元格的值
【发布时间】:2016-06-07 14:35:18
【问题描述】:

我目前有以下工作代码:

for i,gram in enumerate(df['Unigram']):
    for j,word in enumerate(df1['Keyword']):
      if df.ix[i,'Unigram'] in df1.loc[j,'Keyword']:
        df.ix[i,'Cost'] += df1.ix[j,'Cost']

但是对于大型数据集,这需要很长时间。有没有更有效的方法来解决这个问题?我听说 Pandas DataFrames 不喜欢被循环,但不确定最好的方法。一个可行的解决方案将能够解决多个匹配项。

提前致谢!

【问题讨论】:

    标签: python excel loops csv pandas


    【解决方案1】:

    尝试使用str.contains()

    for i,gram in enumerate(df['Unigram']):
        select = df1['Keyword'].str.contains(gram, na=False)
        df.ix[i,'Cost'] += df1[select]['Cost']
    

    【讨论】:

    • 我收到Incompatible indexer with Series 错误——有什么想法吗?
    • 这个:df.ix[i,'Cost'] += df1[select]['Cost']
    【解决方案2】:

    df['Unigram']df1['Keyword'] 是系列对象吗?然后你应该用iteritems() 替换你的enumerate() 调用。示例:使用 df['Unigram'].iteritems() 代替 enumerate(df['Unigram'])。如果它们是 DataFrame 对象,则可以使用 iterrows()。

    【讨论】:

    • 它们是各自DataFrames中的列......这是否使它们成为Series对象?
    • 是的,如果它们是 DataFrame 对象中的列,它们将作为 Series 对象处理。您可以使用print type(df['Unigram']) 对其进行测试。输出应该类似于<class 'pandas.core.series.Series'>
    • 在问题代码中,列('Cost')正在被迭代的行中更新。您不应更改由iteritems()iterrows() 迭代的项目,因为它们可能会返回数据的副本。因此更改迭代项可能不会更改基础数据。 Docs -See the pink warning box
    猜你喜欢
    • 2021-10-06
    • 1970-01-01
    • 2017-08-27
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 2016-02-29
    • 2022-09-23
    相关资源
    最近更新 更多