首页 > 解决方案 > 在 Python 中使用 pandas 导出拆分为多行的用户输入字符串

问题描述

我在 Excel 中有一个列,它有大约 11,500 行,我用来格式化代码以放入 SAS 格式化代码。不幸的是,许多行在文本中都有撇号,所以当我复制它时,它会丢弃我在 Excel 中格式化的添加的撇号。

我思考了这个问题,并想为什么不去掉 Python 中多余的撇号;我遇到了与 Python 相干扰的撇号的类似问题,但我能够通过将字符串作为输入来解决这个问题。在我的条件语句之前,一切都按预期工作——我输入了多个带撇号的单词,它没有返回它们。

此时,我想将去掉撇号的结果导出回 Excel(我知道我可以复制和粘贴,但我不想冒丢失任何数据的风险)。我也可以使用熊猫来做到这一点;问题是,当我定义要导出的数据时,它会将所有数据放在一行中的一个单元格中,而我希望在原始的 ~11,500 行中返回数据。我尝试使用 .split,但没有成功,所以我确信这不是解决方法。有什么建议么??见下文:

#Apostrophe Remover

#Ask user to input the desired text as var1
MyString=str(input("Enter Text Here: "))

#Define var2 as an apostrophe
MySubstring="'"

#Search for apostrophes in entry and remove if applicable; state if not applicable

if MySubstring in MyString:
    MyString = MyString.replace("'", "")
    print()
    print(MyString)
else:
    print()
    print("No apostrophes found!")

#Creating string split by commas as var3    
MyStringSplit=MyString.split(',')
print(MyStringSplit)
    
#Export Python Output to Excel
import pandas as pd

data = {'ICD-10 Code & Description': [MyStringSplit],
        }

df = pd.DataFrame(data, columns = ['ICD-10 Code & Description'])

df.to_excel (r'C:/Users/tjm4q2/Desktop/TM Thesis DX Codes Python Output.xlsx', index = False, header=True)

标签: pythonexcelpandasstringsplit

解决方案


data = {'ICD-10 Code & Description': [MyStringSplit],
        }

我相信您只需要删除方括号,MyStringSplit因为它已经是一个列表。.split()返回一个字符串列表。因为它已经是一个列表,所以在包含方括号时,您将在 pandas 中创建一行:

在此处输入图像描述

相反,你想要

data = {'ICD-10 Code & Description': MyStringSplit,
        }

在此处输入图像描述

顺便说一句,您甚至不需要定义data字典,而是可以删除整行并简单地执行以下操作:

df = pd.DataFrame(MyStringSplit, columns = ['ICD-10 Code & Description'])

推荐阅读