python - 将带有分隔符的数据框展平为变量

标签 python string pandas dataframe

如何将其分配给变量而不是打印它?

print(*df.values.flatten(), sep=',')

最佳答案

我认为如果可能的话需要将一些非字符串列转换为字符串,然后调用join:

a = ','.join(df.astype(str).values.flatten())

示例:

df = pd.DataFrame({
    'A': ['b','b','c','d'],
    'B': list(range(4))
})
print (df)
   A  B
0  b  0
1  b  1
2  c  2
3  d  3

a = ','.join(df.astype(str).values.flatten())
print (a)
b,0,b,1,c,2,d,3

print(*df.values.flatten(), sep=',')
b,0,b,1,c,2,d,3

关于python - 将带有分隔符的数据框展平为变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52519887/

相关文章:

python - 覆盖另一个库的函数的返回值

python - 我想将 Qt QML Combobox 设置为 PyQt5 对象属性

PHP:检查链接是否为图像并检查是否存在

python - Pandas DataFrame 没有完整的数据,而是使用三个点

python - Pandas read_csv 可以将文件锁定在 Windows 上

python - 如果 bool(item) 为真,则将项目添加到 python 字典

python - 使用生成器函数构建列表是否有效

c++ - 格式化 : how to convert 1 to “01” , 2 到 “02” , 3 到 "03",等等

c - 纯C : trim all characters in a string after a word occurs

python - 使用 pandas 数据框中使用多列的多个自定义函数聚合多列的有效方法是什么?