python - 根据字段位置将 Pandas 数据框导出到 txt
问题描述
我有一个pd.DataFrame
我想导出到一个文本文件,该字段由它们的位置/索引定位(不像csv
带分隔符的)。我可以创建一个功能来做到这一点,但它很可能会很慢,我希望 Pandas 能够集成这样的功能。
pd.DataFrame({'a':[1,20,300], 'b':[10,200,30], 'c':[100, 2, 3]})
export(df, index_position={'a':0, 'b':5, 'c':9}, 'sometxtfile.txt')
我期待的输出(我不想要标题)
0123456789012 ## index position as a reference
a b c ## Where the variable must be
------------- ## The file starts after that
1 10 100 ## a is starting at index 0
20 200 2 ## b is starting at index 5
300 30 3 ## c is starting at index 9
任何帮助将不胜感激
解决方案
这行得通,但它不是很优雅。欢迎评论,欢迎批评。
输入数据:
df = pd.DataFrame({'a':[1,20,300], 'b':[10,200,30], 'c':[100, 2, 3]})
positions = {0:'a', 5:'b', 9:'c'}
字符串创建:
def exporttxt(df, positions):
indexes = [x for x in positions.keys()]
indexes.sort()
df = df[[positions[x] for x in indexes]]
toreturn = ''
for _, line in df.iterrows():
newline = ['{}'.format(line[positions[i]]).ljust(l) for i, l in zip(indexes, lengths)]
toreturn = toreturn + '\n' + ''.join(newline)
return toreturn
print(exporttxt(df, positions))
输出:
1 10 100
20 200 2
300 30 3
推荐阅读
- nasm - 无法获得正确的 .ascii 和
- c# - 使用 Entity Framework Core 更新具有特定 id 的不同数据的多行
- pygame - Pygame事件:在不释放按键的情况下触发按键事件
- angular - 在 Capacitor 中保存 pdf 文件
- c++ - 被C++中的排序比较方法迷惑
- image - 当输入变量是大图像时如何使用 Matlab 最小化成本函数:提高速度并防止内存崩溃
- javascript - 将数组转换为单个url参数字符串
- javascript - 如何使用横向卷轴游戏中的方法从数组中删除元素?
- python - 当内部和内部通信器合并时,使用 Spawn() 从 python 生成的 Fortran 子(或 C++ 或 python)进程不会断开连接
- ruby-on-rails - 使用 ruby 脚本将 git repo 克隆到我的系统后,如何存储文件名?