[英]Convert a whole list to string
import pandas as pd
raw_data = {'a': ['a'],'b':['b'],'c':['c'],'d':[['a','b']]}
df = pd.DataFrame(raw_data, columns = ['a','b','c','d'])
this results,这个结果,
a b c d
0 a b c [a, b]
then i'm adding it into a single column like this df['test'] = df['a']+'+'+df['b']+'+'+df['c']
然后我将它添加到这样的单个列
df['test'] = df['a']+'+'+df['b']+'+'+df['c']
df['test'] gives a+b+c
df['test'] 给出
a+b+c
After that I'm fetching each single value using this之后,我使用这个获取每个单个值
finalArr = df['test'][0]
finalArr = finalArr.split("+")
one = finalArr[0]
two = finalArr[1]
three = finalArr[2]
How to add df['d'] to this:如何将 df['d'] 添加到此:
df['test'] = df['a']+'+'+df['b']+'+'+df['c']
and fetch four = finalArr[3]
并获取
four = finalArr[3]
expected output:预期 output:
df['test']
a+b+c+[a,b]
four = finalArr[3]
[a,b]
[a,b] should be in list format while fetching
Use, Dataframe.agg
on axis 1
to join the columns a, b, c
around seperator +
then use Series.str.join
to join the list then concatenate it with square brackets:在轴
1
上使用Dataframe.agg
将列a, b, c
围绕分隔符+
然后使用Series.str.join
加入列表,然后用方括号将其连接起来:
df['test'] = df[['a', 'b', 'c']].agg('+'.join, axis=1) + '+[' + df['d'].str.join(',') + ']'
# print(df)
a b c d test
0 a b c [a, b] a+b+c+[a,b]
# Python program to convert a list to string
# Function to convert
def listToString(s):
# initialize an empty string
str1 = ""
# traverse in the string
for ele in s:
str1 += ele
# return string
return str1
# Driver code
s = ['Geeks', 'for', 'Geeks']
print(listToString(s))
you can simply use this line string=[str(value) for value in df.iloc[0,:]]您可以简单地使用这一行string=[str(value) for value in df.iloc[0,:]]
import pandas as pd
raw_data = {'a': ['a'],'b':['b'],'c':['c'],'d':[['a','b']]}
df = pd.DataFrame(raw_data, columns = ['a','b','c','d'])
string=[str(value) for value in df.iloc[0,:]]
df['test']=pd.Series({0:string})
print(string[3])
"['a', 'b']"
Try this out:试试这个:
s = '[' + df['d'].str.join(', ') + ']' #first convert your list to a string
df['test'][0] += '+' + s #then add it to your variable
The result will be:结果将是:
>>>print(df['test'][0])
"a+b+c+[a, b]"
And then if you want to fetch it as a list, you can use this:然后如果你想把它作为一个列表来获取,你可以使用这个:
arr = df['test'][0].split('+')
arr[3] = arr[3][1:-1].split(', ') #convert the string to a list.
# [1: -1] removes the brackets ('[', ']')
# you can also use .strip('[]') instead
Good luck with your project;)祝你的项目好运;)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.