简体   繁体   English

使用to_csv时如何删除元组中的str“Pandas”和键名?

[英]how to drop the str "Pandas" and the key name in the tuple when using to_csv?

I have a DataFrame like the below, and I get the df by using DataFrame.itertuples() function我有一个 DataFrame 如下所示,我通过使用 DataFrame.itertuples() function 获得 df

    columnName                   
0   (CJ, 2, 1.0, 31, 34.46)
1   (CJ, 2, 1.0, 31, 34.46)
2   (CJ, 2, 1.0, 31, 34.46)

when I use the to_csv() function, I get the csv file like this:当我使用 to_csv() function 时,我得到 csv 文件,如下所示:

   columnName
0  Pandas(Index='CJ', position=2, pos_options=1.0, salary=31, Value=34.46)
1  Pandas(Index='CJ', position=2, pos_options=1.0, salary=31, Value=34.46)
2  Pandas(Index='CJ', position=2, pos_options=1.0, salary=31, Value=34.46)

how can I dorp the annoying "Pandas","index=","position=", "pos_options=","salary=", "Value="? They are filled with the csv table and affect the human reading.我怎样才能 dorp 烦人的“Pandas”,“index =”,“position =”,“pos_options =”,“salary =”,“Value =”?它们充满了 csv 表并影响人类阅读。

what I want is the simple expressions like this:我想要的是这样的简单表达式:

    columnName                   
0   CJ, 2, 1.0, 31, 34.46
1   CJ, 2, 1.0, 31, 34.46
2   CJ, 2, 1.0, 31, 34.46

You can use strip() method:您可以使用strip()方法:

df['columnName']=df['columnName'].astype(str).str.strip('()')

Now if you print df you will get:现在如果你打印df你会得到:

    columnName
0   'CJ', 2, 1.0, 31, 34.46
1   'CJ', 2, 1.0, 31, 34.46
2   'CJ', 2, 1.0, 31, 34.46

EDIT: If you have many columns then use apply() method:编辑:如果你有很多列,那么使用apply()方法:

df=df.apply(lambda x:x.astype(str).str.strip('()'),1)

Finally use to_csv() method最后使用to_csv()方法

df.to_csv('filename.csv')

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

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