【问题标题】:concatenate column values in a loop在循环中连接列值
【发布时间】:2019-06-30 16:30:38
【问题描述】:

我有一个包含两列的 csv 文件:

  col1   col2
 ----- | -----
  link1  unix=number1  
  link2  unix=number2  
  link3  unix=number3    

我需要什么:

我需要将 col1 中的每个值与 col2 中的每个值连接起来才能得到以下结果:

ecol1   col2           col3
----- | -----      |   ----
 link1  unix=number1  link1unix=number1
 link2  unix=number2  link1unix=number2
 link3  unix=number2  link1unix=number3
 link4  NAN           link2unix=number1
 link5  NAN           link2unix=number2
 link6  NAN           link2unix=number3
                      etc ..  

这是我的代码,但它不起作用:

i = 0
while True:
  df= pd.read_csv('file.csv', skiprows=lambda x: x in range(0,i))
  for i, row in df.iterrows():  
    row = df['col1'] + df['col2']
    i+=1

请帮忙

【问题讨论】:

    标签: python-3.x pandas loops


    【解决方案1】:

    用途:

    import itertools
    df['col3']=[''.join(i) for i in list(itertools.product(df['col1'],df['col2']))]
    

    编辑:

    l= [''.join(i) for i in list(itertools.product(df1.col1,df1.col2))]
    df=df.reindex(range(len(l)))
    df['col3']=l
    print(df)
    
      col1 col2 col3
    0    a    x   ax
    1    b    y   ay
    2    c    z   az
    3  NaN  NaN   bx
    4  NaN  NaN   by
    5  NaN  NaN   bz
    6  NaN  NaN   cx
    7  NaN  NaN   cy
    8  NaN  NaN   cz
    

    【讨论】:

    • Col2 是一个数字,会有什么不同吗?
    • 是的,使用[''.join(i) for i in list(itertools.product(df['col1'].astype(str),df['col2'].astype(str)))]
    • 给我ValueError: Length of values does not match length of index - 我修改了两列的长度,以便它们可以是相同的索引长度,但它仍然无法正常工作。
    • 是的,如果你下面没有任何数据,你想如何用NAN填充数据?
    • @J.Doe 检查编辑部分
    猜你喜欢
    • 2019-01-05
    • 1970-01-01
    • 2013-05-16
    • 2021-08-27
    • 2019-04-14
    • 1970-01-01
    • 2018-06-26
    • 1970-01-01
    相关资源
    最近更新 更多