【问题标题】:python pandas iterating rows of two different columns and returning the repeated one once and corresponding values of repeated values in single rowpython pandas迭代两个不同列的行并返回重复的一次和单行中重复值的对应值
【发布时间】:2020-06-13 01:23:27
【问题描述】:

例如,我有一个包含 1000 行的 .csv 文件,如下所示:

year,name
1992,Alex
1992,Anna
1993,Max
1993,Bob
1993,Tom

等等……

我希望我的输出是:

   year           name
   1992     Alex, Anna
   1993  Max, Bob, Tom

这看起来很简单,但我无法在单行中添加一个逗号',' 的相应行

【问题讨论】:

  • 嗨,欢迎来到 SO。你能编辑你的例子吗?它很容易被误解。 stackoverflow.com/questions/20109391/…
  • 现在清楚了吗?
  • 请提供你得到的桌子和你想要的东西。因为我不明白你想在这里做什么。

标签: python pandas loops csv


【解决方案1】:

您可以通过使用 groupby 和聚合来实现这一点。试试下面的代码:

df = df.groupby("year").agg({
    "year":"first",
    "name":", ".join
                          })

您可以通过忽略索引将数据框值保存到 csv

df.to_csv("output.csv",index=False)

【讨论】:

  • 是agg函数之一。取组中的第一次出现。
【解决方案2】:

这可能对你有帮助

df = df.groupby('year')['name'].unique().reset_index()
df['name'] = df['name'].apply(lambda x: ', '.join(x))

输出:

   year           name
0  1992     Alex, Anna
1  1993  Max, Bob, Tom

【讨论】:

    【解决方案3】:

    这个怎么样?

    import pandas as pd
    x = pd.DataFrame.from_dict({'year':['1992', '1992', '1993', '1993', '1993'], 
                                'name':['ALEX', 'ANNA', 'MAX', 'BOB', 'TOM'],
                                 'col':range(5)})
    print (x)
    
    a = x.groupby('year').agg({'name': lambda x: tuple(set(x)), 'col':'sum'})
    print (a)
    

    结果:

                     name  col
    year                      
    1992     (ALEX, ANNA)    1
    1993  (BOB, TOM, MAX)    9
    

    【讨论】:

      猜你喜欢
      • 2013-05-23
      • 1970-01-01
      • 2016-10-23
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 2019-03-25
      • 2019-02-10
      • 2019-01-25
      相关资源
      最近更新 更多