Emi*_*l H 230 python csv string csv-import pandas
为了测试一些功能,我想DataFrame从一个字符串创建一个.假设我的测试数据如下:
TESTDATA="""col1;col2;col3
1;4.4;99
2;4.5;200
3;4.7;65
4;3.2;140
"""
Run Code Online (Sandbox Code Playgroud)
将数据读入熊猫的最简单方法是什么DataFrame?
Emi*_*l H 414
一种简单的方法是使用StringIO.StringIO并将其传递给io.StringIO函数.例如:
import sys
if sys.version_info[0] < 3:
from StringIO import StringIO
else:
from io import StringIO
import pandas as pd
TESTDATA = StringIO("""col1;col2;col3
1;4.4;99
2;4.5;200
3;4.7;65
4;3.2;140
""")
df = pd.read_csv(TESTDATA, sep=";")
Run Code Online (Sandbox Code Playgroud)
小智 19
一行,但先导入IO
import pandas as pd
import io
TESTDATA="""col1;col2;col3
1;4.4;99
2;4.5;200
3;4.7;65
4;3.2;140
"""
df = pd.read_csv( io.StringIO(TESTDATA) , sep=";")
print ( df )
Run Code Online (Sandbox Code Playgroud)
分割法
data = input_string
df = pd.DataFrame([x.split(';') for x in data.split('\n')])
print(df)
Run Code Online (Sandbox Code Playgroud)
交互式工作的一种快速简便的解决方案是通过从剪贴板加载数据来复制和粘贴文本。
用鼠标选择字符串的内容:
在Python Shell中使用 read_clipboard()
>>> pd.read_clipboard()
col1;col2;col3
0 1;4.4;99
1 2;4.5;200
2 3;4.7;65
3 4;3.2;140
Run Code Online (Sandbox Code Playgroud)
使用适当的分隔符:
>>> pd.read_clipboard(sep=';')
col1 col2 col3
0 1 4.4 99
1 2 4.5 200
2 3 4.7 65
3 4 3.2 140
>>> df = pd.read_clipboard(sep=';') # save to dataframe
Run Code Online (Sandbox Code Playgroud)
传统的可变宽度CSV无法将数据存储为字符串变量。尤其是在.py文件内部使用时,请考虑使用定宽管道分隔的数据。各种IDE和编辑器可能都有一个插件,用于将管道分隔的文本格式化为整齐的表。
以下对我有用。要使用它,请将其存储到文件中,例如pandas_util.py。函数的文档字符串中包含一个示例。如果您使用的Python版本早于3.6,请从函数定义行中删除类型注释。
import re
import pandas as pd
def read_pipe_separated_str(str_input: str, **kwargs) -> pd.DataFrame:
"""Read a Pandas object from a pipe-separated table contained within a string.
Example:
| int_score | ext_score | eligible |
| | 701 | True |
| 221.3 | 0 | False |
| | 576 | True |
| 300 | 600 | True |
The leading and trailing pipes are optional, but if one is present, so must be the other.
`kwargs` are passed to `read_csv`. They must not include `sep`.
In PyCharm, the "Pipe Table Formatter" plugin has a "Format" feature that can be used to neatly format a table.
"""
# Ref: /sf/answers/3253036671/
substitutions = [
('^ *', ''), # Remove leading spaces
(' *$', ''), # Remove trailing spaces
(r' *\| *', '|'), # Remove spaces between columns
]
if all(line.lstrip().startswith('|') and line.rstrip().endswith('|') for line in str_input.strip().split('\n')):
substitutions.extend([
(r'^\|', ''), # Remove redundant leading delimiter
(r'\|$', ''), # Remove redundant trailing delimiter
])
for pattern, replacement in substitutions:
str_input = re.sub(pattern, replacement, str_input, flags=re.MULTILINE)
return pd.read_csv(pd.compat.StringIO(str_input), sep='|', **kwargs)
Run Code Online (Sandbox Code Playgroud)
下面的代码无法正常工作,因为它在左右两侧都添加了一个空列。
df = pd.read_csv(pd.compat.StringIO(df_str), sep=r'\s*\|\s*', engine='python')
Run Code Online (Sandbox Code Playgroud)