pandas 字符串拼接问题

2022-01-21 13:59:38 +08:00
 toyst
import pandas as pd
df = pd.DataFrame(columns = ['a', 'b', 'c'],
             data=[['A','1','http:1'],
                   ['B', '2','http:2'],
                   ['C', '3','http:3'],
                   ['D','4','http:4']])
print(df)
   a  b       c
0  A  1  http:1
1  B  2  http:2
2  C  3  http:3
3  D  4  http:4

我想输出:

#Result
G "A","1"
http:1
G "B","2"
http:2
G "C","3"
http:3
G "D","4"
http:4

这样的格式,应该怎么拼接输出啊

2331 次点击
所在节点    Python
6 条回复
tfdetang
2022-01-21 14:38:20 +08:00
这不就是行循环一下 把每列的内容放到格式化的字符串里就行了吗
toyst
2022-01-21 16:35:05 +08:00
@tfdetang 关键是这个 http:1 是个回车怎么拼接啊
zhusimaji
2022-01-21 16:39:33 +08:00
@toyst 回车自己加个\n
cclin
2022-01-21 16:45:40 +08:00
拿去抄吧
def combine(line: pd.Series):
print(line)
return f'G "{line.a}","{line.b}"\n{line.c}'


df = df.apply(combine, axis=1)

for s in list(df):
print(s)
cassidyhere
2022-01-21 16:46:09 +08:00
'G "' + df.a + '","' + df.b + '"\n' + df.c
toyst
2022-01-21 16:55:28 +08:00
感谢大家,原来输出到文本\n 就能显示换行符了

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/829684

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX