用熊猫导出数据

时间:2018-10-30 10:28:13

标签: python pandas

我在excel文件的一栏中应用了一种处理方法。现在,我要导出此处理过的列以及所有其他未处理过的列。

我的数据(小示例):

       A          B                                    C
  French      house                Phone <phone_numbers>
 English      house            email blablabla@gmail.com
  French  apartment                      my name is Liam
  French      house                         Hello George
 English  apartment   Ethan, my phone is <phone_numbers>

我的脚本:

import re
import pandas as pd
from pandas import Series

df = pd.read_excel('data.xlsx')
data = Series.to_string(df['C'])

def emails(data):

    mails = re.compile(r'[\w\.-]+@[\w\.-]+')
    replace_mails = mails.sub('<adresse_mail>', data)

    return replace_mails

no_mails = emails(data)
no_mails.to_excel('new_data.xlsx')

我的输出:

AttributeError                            Traceback (most recent call last)
<ipython-input-7-8fd973998937> in <module>()
      7 
      8 no_mails = emails(data)
----> 9 no_mails.to_excel('new_data.xlsx')

AttributeError: 'str' object has no attribute 'to_excel'

好的输出:

       A          B                                    C
  French      house                Phone <phone_numbers>
 English      house                 email <adresse_mail>
  French  apartment                      my name is Liam
  French      house                         Hello George
 English  apartment   Ethan, my phone is <phone_numbers>

我的脚本只能正常工作

no_mails.to_excel('new_data.xlsx')

似乎不起作用。

4 个答案:

答案 0 :(得分:2)

尝试一下

no_mails= pd.DataFrame({'email' : []}) no_mails['email'] = emails(data) no_mails.to_excel('new_data.xlsx')

答案 1 :(得分:2)

您可以在熊猫系列上使用replace

df['C'] = df['C'].str.replace(r'[\w\.-]+@[\w\.-]+','<adresse_mail>')
df.to_excel('new_data.xlsx')

答案 2 :(得分:1)

函数似乎返回一个String。您应该将其转换为DataFrame。

如果要对DataFrame执行正则表达式,则应尝试以下操作:

result = df['C'].str.findall(r'[\w\.-]+@[\w\.-]+')
writer = pd.ExcelWriter('new_data.xls')
result.to_excel(writer, 'Sheet 1')
writer.save()

答案 3 :(得分:1)

to_excel是熊猫数据框方法doc。您应该在数据帧上执行替换,而不是在提取为字符串的列上执行替换(就像您对Series.to_string(df['C'])所做的那样)。

粘贴到数据框上,您应该会很好。