简体   繁体   English

将字符串附加到列表中的字符串

[英]Append a String to a String in a List

I am reading an excel table: 我正在阅读一张excel表:

在此输入图像描述

import pandas as pd

df = pd.read_excel('file.xlsx', usecols = 'A,B,C')
print(df)

Now I want to create a list with every row in the table as string. 现在我想创建一个列表,其中表中的每一行都是字符串。 In addition I want to add a 'X' at the end of every string in the list: 另外我想在列表中的每个字符串的末尾添加一个'X':

keylist = []
list1, list2, list3 = df['A'].tolist(), df['B'].tolist(), df['C'].tolist()

for i in zip(list1, list2, list3):
    val = map(str, i)
    keylist.append('/'.join(val))
    keylist += 'X'

print(keylist)

Everything works except the 'adding a X' part. 一切都有效,除了“添加X”部分。 This results in: 这导致:

['blue/a/a1', 'X', 'blue/a/a2', 'X', ....

But what I want is: 但我想要的是:

['blue/a/a1/X', 'blue/a/a2/X',

Thanks beforehand. 先谢谢。

I think better is: 我认为更好的是:

d = {'A': ['blue', 'blue', 'blue', 'red', 'red', 'red', 'yellow', 
           'yellow', 'green', 'green', 'green'],
     'B': ['a', 'a', 'b', 'c', 'c', 'c', 'd', 'e', 'f', 'f', 'g'], 
     'C': ['a1', 'a2', 'b1', 'c1', 'c2', 'c3', 'd1', 'e1', 'f1', 'f2', 'g1']}
df = pd.DataFrame(d)
print (df)
         A  B   C
0     blue  a  a1
1     blue  a  a2
2     blue  b  b1
3      red  c  c1
4      red  c  c2
5      red  c  c3
6   yellow  d  d1
7   yellow  e  e1
8    green  f  f1
9    green  f  f2
10   green  g  g1

keylist = df.apply(lambda x: '/'.join(x), axis=1).add('/X').values.tolist()
print (keylist)

['blue/a/a1/X', 'blue/a/a2/X', 'blue/b/b1/X', 'red/c/c1/X', 'red/c/c2/X', 
 'red/c/c3/X', 'yellow/d/d1/X', 'yellow/e/e1/X', 
 'green/f/f1/X', 'green/f/f2/X', 'green/g/g1/X']

Or if only few columns: 或者如果只有几列:

keylist = (df['A'] + '/' + df['B'] + '/' + df['C'] + '/X').values.tolist()

Some timing s: 一些时间

#[110000 rows x 3 columns]
df = pd.concat([df] * 10000, ignore_index=True)

In [364]: %%timeit
     ...: (df['A'] + '/' + df['B'] + '/' + df['C'] + '/X').values.tolist()
     ...: 
60.2 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [365]: %%timeit
     ...: df.apply(lambda x: '/'.join(x), axis=1).add('/X').tolist()
     ...: 
2.48 s ± 39.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)


In [366]: %%timeit
     ...: list1, list2, list3 = df['A'].tolist(), df['B'].tolist(), df['C'].tolist()
     ...: for i in zip(list1, list2, list3):
     ...:     val = map(str, i)
     ...:     keylist.append('/'.join(val))
     ...:     keylist[-1] += '/X'
     ...: 
192 ms ± 78.5 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [367]: %%timeit
     ...: df.iloc[:,0].str.cat([df[c] for c in df.columns[1:]],sep='/').tolist()
     ...: 
61.1 ms ± 540 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [368]: %%timeit
     ...: df.assign(New='X').apply('/'.join,1).tolist()
     ...: 
2.51 s ± 76.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [369]: %%timeit
     ...: ['{0}/{1}/{2}/X'.format(i, j, k) for i, j, k in df.values.tolist()]
74.6 ms ± 2.27 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

You are doing += do the keylist which adds to that list, you need to do it to the val array. 你正在做+ =做添加到该列表的密钥列表,你需要对val数组做。

for i in zip(list1, list2, list3):
  val = map(str,i)
  val += 'X' # you can combine this and the above if you want to look like:
  #val = map(str, i) + 'X'
  keylist.append("/".join(val))
print(keylist)

Here is one way using a list comprehension with str.format : 以下是使用str.format的列表str.format一种方法:

res = ['{0}/{1}/{2}/X'.format(i, j, k) for i, j, k in df.values.tolist()]

# ['blue/a/a1/X', 'blue/a/a2/X', 'blue/b/b1/X', 'red/c/c1/X', ...]

There is no need, as in this solution, to split into 3 lists and zip them. 如此解决方案中一样,不需要拆分为3个列表并将其zip

Base on pandas 基于pandas

df.assign(New='X').apply('/'.join,1).tolist()
Out[812]: ['blue/a/a1/X', 'blue/a/a2/X', 'blue/b/b1/X']

You could add /X to last item in list everytime in the loop: 您可以在循环list每次将/X添加到list中的最后一项:

for i in zip(list1, list2, list3):
    val = map(str, i)
    keylist.append('/'.join(val))
    keylist[-1] += '/X'

# ['blue/a/a1/X', 'blue/a/a2/X',....]

You can use the cat string operation to join the columns into a single series with a specified sep argument. 您可以使用cat string操作将列连接到具有指定sep参数的单个系列。 Then simply convert the new series into a list 然后只需将新系列转换为列表即可

 df
         A  B   C
0     blue  a  a1
1     blue  a  a2
2     blue  b  b1
3      red  c  c1
4      red  c  c2
5      red  c  c3
6   yellow  d  d1
7   yellow  e  e1
8    green  f  f1
9    green  f  f2
10   green  g  g1

df.iloc[:,0].str.cat([df[c] for c in df.columns[1:]],sep='/').tolist()

['blue/a/a1', 'blue/a/a2', 'blue/b/b1', 'red/c/c1', 'red/c/c2', 'red/c/c3', 'yellow/d/d1', 'yellow/e/e1', 'green/f/f1', 'green/f/f2', 'green/g/g1']

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM