简体   繁体   English

将具有逗号分隔字符串的 2 列合并为 pandas 中的 1 列

[英]Combine 2 columns which are having comma separated strings into 1 column in pandas

I have a dataframe我有一个 dataframe

df = pd.DataFrame([["A","a$b,c$d,k$m","h,y,a"], ["B","n$e,d$w,t$y","t,r,s"]], columns=["id","c1","c2"])

I want to combine each element of column c1 which are separated by a comma with another element of column c2 with an asterisk(*)我想将用逗号分隔的 c1 列的每个元素与带有星号 (*) 的 c2 列的另一个元素组合起来

Expected output:预期 output:

df_out = pd.DataFrame([["A","a$b*h,c$d*y,k$m*a"], ["B","n$e*t,d$w*r,t$y*s"]], columns=["id","c3"])

How to do it?怎么做?

You can try out the below code.你可以试试下面的代码。

df = pd.DataFrame([["A","a$b,c$d,k$m","h,y,a"], ["B","n$e,d$w,t$y","t,r,s"]], columns=["id","c1","c2"])

def combine_list(a, b):
          return (',').join([i+'*'+j for i, j in zip(a, b)])
        
df['c3'] = df.apply(lambda x: combine_list(x['c1'].split(','), x['c2'].split(',')), axis=1)
df_out = df[["id", "c3"]]

Hope this solves your query!希望这能解决您的疑问!

Use nested list comprehension with DataFrame.pop for extract values and zip , for add * is used f-string s and last join in join :使用嵌套列表理解与DataFrame.pop提取值和zip ,对于 add *使用f-string s 和最后加入join

df['c3'] = [','.join(f'{i}*{j}' for i, j in zip(x.split(','), y.split(',')))
                                for x, y in zip(df.pop('c1'), df.pop('c2'))]
print (df)
  id                 c3
0  A  a$b*h,c$d*y,k$m*a
1  B  n$e*t,d$w*r,t$y*s
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 pandas 的单个列中合并(逗号分隔的)行值? - How to combine (comma-separated) row values in a single column in pandas? 将逗号分隔字符串的熊猫列转换为整数 - Converting pandas column of comma-separated strings into integers 将逗号分隔字符串的 pandas 列转换为虚拟变量 - Converting pandas column of comma-separated strings into dummy variables Parsiing DF列具有多个逗号分隔标签到各个列中 - Parsiing DF column having multiple comma separated labels into the individual columns pandas 合并列以使用逗号分隔值创建新列 - pandas merge columns to create new column with comma separated values 根据 pandas 中的特定条件拆分以逗号分隔的列 - Split a column which is separated by comma based on certain condition in pandas 将两列以逗号分隔的字符串合并为一列,并具有唯一性 - Combine two columns with comma delimited strings into one column with joined unique 熊猫-如何用逗号分隔的字符串分隔和分组 - Pandas - How to separate and group by comma separated strings 为pandas行中的逗号分隔字符串生成组合 - Generate combinations for a comma separated strings in a pandas row 将包含空字符串的列合并为 python pandas 中的一列 - combine columns containing empty strings into one column in python pandas
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM