如何使用大熊猫替换Excel数据中的某些值?
我有一个简短的python脚本,它使用pandas
读取Excel文件,然后创建sql insert
命令。
在脚本中,我需要替换某些字符字符串。
但是,当我这样做时,我会收到此错误:
AttributeError: 'Pandas' object has no attribute 'replace'
这是我的脚本:
import pandas as pd
df = pd.read_excel('JulyData.xlsx')
# print(df)
# print(df.iloc[0, 0])
print('INSERT INTO project(name, object, amount, value)')
for row in df.itertuples(index=False):
rowString = row
rowString = rowString.replace(' " ', " ")
rowString = rowString.replace(' – ', " ")
rowString = rowString.replace(' / ', " & ")
rowString = rowString.replace(' ’ ', " ")
print(f'VALUES {tuple(rowString)}')
print(f'WAITFOR DELAY \'00:00:02\'')
print('\n')
有没有办法在pandas
中做到这一点?
谢谢!
样本输出:
{'name': ['Xu–, Yi', 'Gare, /Mark'], 'object': ['xuy@anes’.mty.edu', '"[email protected]'], 'amount': ['100', '200'], 'value': ['"abc"', 'def']}
I have a short Python script that uses pandas
to read an Excel file and then create a SQL INSERT
command.
Inside the script, I need to replace certain character strings.
However, when I do, I get this error:
AttributeError: 'Pandas' object has no attribute 'replace'
Here is my script:
import pandas as pd
df = pd.read_excel('JulyData.xlsx')
# print(df)
# print(df.iloc[0, 0])
print('INSERT INTO project(name, object, amount, value)')
for row in df.itertuples(index=False):
rowString = row
rowString = rowString.replace(' " ', " ")
rowString = rowString.replace(' – ', " ")
rowString = rowString.replace(' / ', " & ")
rowString = rowString.replace(' ’ ', " ")
print(f'VALUES {tuple(rowString)}')
print(f'WAITFOR DELAY \'00:00:02\'')
print('\n')
Is there a way to do this in pandas
?
Thanks!
sample output:
{'name': ['Xu–, Yi', 'Gare, /Mark'], 'object': ['xuy@anes’.mty.edu', '"[email protected]'], 'amount': ['100', '200'], 'value': ['"abc"', 'def']}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
pandas
是名为Tuple的名称ROW
由Internows
返回,并且名为Tupuple当然没有方法replace>替换
。您需要的是PANDAS方法 (对于整个数据框架)或字符串评估器的单个列)。示例:
结果:
Pandas
is the name of the namedtuplerow
returned byinterrows
, and a namedtuple of course has no methodreplace
. What you need is the pandas methodreplace
(for the whole data frame) or the string assessor'sreplace
(for individual columns).Example:
Result: