pandas 如何为保存为 CSV 的数据框的非数字列中的每个元素添加引号“”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/41960346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add quotes " " to every element in non numeric column of a dataframe saved as CSV
提问by Ekaterina
I have DataFrame
我有数据框
id,type,value
1,8,value1
2,2,value2
3,7,value3
4,3,value4
5,10,value5
6,3,value16
I want to add to the value id
and value
of the CSV file to be allocated quotes
我想添加到要分配的 CSV 文件的值id
和value
引号
"1",8,"value1"
"2",2,"value2"
What better way to do it
有什么更好的方法来做到这一点
回答by Boud
Convert you id column as a string column. Then use the appropriate arguments in function to_csv
:
将您的 id 列转换为字符串列。然后在函数中使用适当的参数to_csv
:
import csv
df.id = df.id.astype(str)
df.to_csv('test.txt', index=False, quotechar='"',
header=None, quoting=csv.QUOTE_NONNUMERIC)
csv.QUOTE_NONNUMERIC
will apply quotes to all columns that are obviously non numeric like int or float.
csv.QUOTE_NONNUMERIC
将引号应用于所有明显非数字的列,如 int 或 float。
回答by piRSquared
converting to strings and using +
转换为字符串并使用 +
df.update('"' + df[['id', 'value']].astype(str) + '"')
print(df)
using applymap
使用 applymap
df.update(df[['id', 'value']].applymap('"{}"'.format))
print(df)
Both yield
两者产量
id type value
0 "1" 8 "value1"
1 "2" 2 "value2"
2 "3" 7 "value3"
3 "4" 3 "value4"
4 "5" 10 "value5"
5 "6" 3 "value16"