[英]Convert all rows of a Pandas dataframe column to comma-separated values with each value in single quote
I have a Pandas dataframe similar to:我有一个类似于以下内容的 Pandas 数据框:
df = pd.DataFrame(['a', 'b', 'c', 'd'], columns=['Col'])
df
Col
0 a
1 b
2 c
3 d
I am trying to convert all rows of this column to a comma-separated string with each value in single quotes, like below:我试图将此列的所有行转换为逗号分隔的字符串,每个值都用单引号括起来,如下所示:
'a', 'b', 'c', 'd'
I have tried the following with several different combinations, but this is the closest I got:我尝试了以下几种不同的组合,但这是我得到的最接近的:
s = df['Col'].str.cat(sep="', '")
s
"a', 'b', 'c', 'd"
I think that the end result should be:我认为最终的结果应该是:
"'a', 'b', 'c', 'd'"
A quick fix will be快速修复将是
"'" + df['Col1'].str.cat(sep="', '") + "'"
"'a', 'b', 'c', 'd'"
另一种选择是使用额外的引号添加每个元素,然后使用默认的.join
;
', '.join([f"'{i}'" for i in df['Col1']])
"'a', 'b', 'c', 'd'"
尝试这个:
s = df['Col'].tolist()
Try something like this:尝试这样的事情:
df = pd.DataFrame(['a', 'b', 'c', 'd'], columns=['Col1'])
values = df['Col1'].to_list()
with_quotes = ["'"+x+"'" for x in values]
','.join(with_quotes)
Output:输出:
"'a','b','c','d'"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.