【问题标题】:Set Value for a Particular column in duplicated DataFrame using index使用索引为重复的 DataFrame 中的特定列设置值
【发布时间】:2020-08-07 20:23:51
【问题描述】:

我创建了一个 Pandas 数据框

import pandas as pd
students = [('jack', 34, 'Sydeny'),
            ('Riti', 30, 'Delhi'),
            ('Aadi', 16, 'New York'),
            ('Riti', 30, 'Delhi'),
            ('Riti', 30, 'Delhi'),
            ('Riti', 30, 'Mumbai'),
            ('Aadi', 40, 'London'),
            ('Sachin', 30, 'Delhi')
            ]

# Create a DataFrame object
dfObj = pd.DataFrame(students, columns=['Name', 'Age', 'City'])

我想从上面的 DataFrame 中找到重复值,所以使用 inbuild duplicated() 来查找重复值

duplicateRowsDF = dfObj[dfObj.duplicated()]

得到了这个

Duplicate Rows except first occurrence based on all columns are :
   Name  Age   City
3  Riti   30  Delhi
4  Riti   30  Delhi

然后我想更改 duplicateRowsDF Name 列中的值,所以我尝试遍历 duplicateRowsDF

for i in range(len(duplicateRowsDF)):
    duplicateRowsDF.at[i,'Name']= 'rohit'

但 duplicateRowsDF 的内容并没有改变,而是添加了两个带有新索引的新闻行

 Name   Age   City
3   Riti  30.0  Delhi
4   Riti  30.0  Delhi
0  rohit   NaN    NaN
1  rohit   NaN    NaN

我想要像

这样的输出
Name   Age   City
    3   rohit  30.0  Delhi
    4   rohit  30.0  Delhi

有什么建议吗?

【问题讨论】:

    标签: python-3.x pandas dataframe duplicates


    【解决方案1】:

    您可以使用DataFrame.copy 在过滤后的DataFrame 中创建新列,以避免可能出现SettingWithCopyWarning

    duplicateRowsDF = dfObj[dfObj.duplicated()].copy()
    duplicateRowsDF['Name'] = 'rohit'
    

    或者使用DataFrame.assign:

    duplicateRowsDF = dfObj[dfObj.duplicated()].assign(Name='rohit')
    

    您的解决方案是可行的,但使用 DataFrame.iatIndex.get_loc 的位置会很慢:

    for i in range(len(duplicateRowsDF)):
        duplicateRowsDF.iat[i,duplicateRowsDF.columns.get_loc('Name')]= 'rohit'
    

    【讨论】:

    • 我喜欢 assign 部分,因为它创建了一个全新的数据,并且避免了 copy(),并将所有内容放在一行中
    【解决方案2】:

    您不需要循环,只需使用 .loc

    duplicateRowsDF = dfObj.loc[dfObj.duplicated()]
    duplicateRowsDF.loc[:,'Name'] = 'rohit'
    
        Name    Age City
    3   rohit   30  Delhi
    4   rohit   30  Delhi
    

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 2012-11-30
      • 2016-02-19
      • 1970-01-01
      • 2016-11-30
      • 2023-01-03
      • 1970-01-01
      • 2015-10-12
      • 1970-01-01
      相关资源
      最近更新 更多