python - 在 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)
解决方案
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'])
推荐阅读
- javascript - 如何使用 Webpack 5 加载服务工作者?
- flutter - 有状态小部件颤动中的未定义名称“小部件”
- reactjs - 如何在带有 RefForwardingComponent 的反应函数组件中使用泛型?
- go - Golang H2C Server 不写全文。Chrome 说:“服务器重置流”。仅通过 http2 连接发生
- php - Laravel 7 下拉列表公共函数创建
- python - NameError:当我尝试捕获执行时,未定义名称“variable_name”
- c - 将文件从客户端发送到服务器 C 不工作 file_desc 未知原因返回 -1
- c# - 如果循环中的索引超出范围,则在 C# 中返回空数组
- android - 无法解析配置“:app debug Runtime Classpath”的所有依赖项
- javascript - 每次使用 React 组件时,是否都会重新评估在 React 组件中定义的辅助函数?