python - 您如何选择将基于索引的信息放入 pandas DataFrame 的位置?
问题描述
在 MATLAB 中,我创建的循环如下所示:
header_names = {'InvoiceNo','Customer',...}
for i = 1:length(x)
entry(index+i,:) = [InvoiceNo, Customer,...]
end
% Create a table from the data.
fin_table = cell2table(entry,'VariableNames',header_names);
% Write to the finish file.
writetable(fin_table,finish);
使用表值和标题,我最终会得到如下所示的内容:
发票号码 | 顾客 |
---|---|
1000 | 吉米 |
1001 | 鲍勃 |
1002 | 最大限度 |
1003 | 四月 |
1004 | 汤姆 |
... | ... |
... | ... |
... | ... |
... | ... |
我想知道如何在 Python 中实现这一点。我的主要问题是如何创建条目?如何将表放在 for 循环中并要求它在每次迭代的下一行打印信息?
在 Python 中,我目前有以下内容:
for i in range(len(item)):
entry = pd.DataFrame(
[InvoiceNo, Customer, invoice, due, terms, Location, memo, item[i], item[i], quan[i], rate[i], taxable,
tax_rate, invoice, email, Class],
columns=['InvoiceNo', 'Customer', 'InvoiceDate', 'DueDate', 'Terms', 'Location', 'Memo', 'Item',
'ItemDescription', 'ItemQuantity', 'ItemRate', 'ItemAmount', 'Taxable', 'TaxRate',
'ServiceDate', 'Email', 'Class'])
# Increment the index for entry values to be correct.
index += len(item)
任何帮助都是极好的!
解决方案
尽管我没有完全理解您的问题,但我会尝试为您提供一些可能有用的工具:
要获取您可以使用的输入值(并根据您要创建的行数将其放入“for”循环中)
new_InvoiceNo= input("Enter InvoiceNo:\n")
new_Customer= input("Enter Customer:\n")
new_invoice = input("Enter invoice:\n")
...
那么您可以将这些值作为列表附加到主 DF 中:
to_append = [new_InvoiceNo, new_Customer, new_invoice, ...]
new_values = pd.Series(to_append, index = df.columns)
df = df.append(new_values , ignore_index=True)
或者,您可以使用 '.loc' 方法:
to_append = [new_InvoiceNo, new_Customer, new_invoice, ...]
df_length = len(df)
df.loc[df_length] = to_append
尝试在您的代码中实现这一点并在此处报告。
推荐阅读
- c++ - 不懂 JLospinoso 书籍的模板实现
- r - R:在 visNetwork 中保留相同的默认颜色集,即使缺少组
- c++ - 为什么双向/正向运算符不支持不等式关系运算符?
- xml - 如何在没有单独结构的情况下获取 xml 名称标签变体
- javascript - 如何使用反应对保存在 EC2 实例上的图像进行旋转然后保存方向
- c++ - 为什么我可以将字符分配给字符串对象而不是字符串对象的向量?
- android - 如何在android中获取帐户列表?
- ios - #SwiftUI 如何创建“添加任务”按钮,如 iOS 提醒应用
- r - 在R中绘制多年的累积数据
- mysql - 如何通过 laravel 插入产品多张图片?