我正在尝试
pandas
,但在使用 concat()
(而不是已弃用的 append()
)来填充大量 DataFrame
时遇到了问题 Series
,名称应该取自(移动)自每个 Series
的某个值(类似于 DataFrame.set_index()
)
以下代码有效,但我不知道如何以正确的
pandas
用法复制它:
_collection = pd.DataFrame()
with open(filename) as _f:
for _line in _f.readlines():
# Parse the line into a dictionary
# e.g: {"Worker ID": 123, "Name": "John Smith", "Salary ($)": 1000}
_entry = re.match(RE_ENTRY, _line).groupdict()
# Append the dictionary to _collection using pd.concat()
_collection= pd.concat([_collection, pd.Series(_entry, name=_entry.pop("Work ID"))], axis=1)
return _collection
我发现用将
name=_entry.pop("Work ID")
更改为 return _collection
来替换 return _collection.T.set_index("Work ID").T
解决方法,但这似乎是多余的......
我假设有一种更干净的方法可以用
pandas
来做到这一点,但不可否认的是我对此知之甚少!
P.S:可能有一个列表理解解决方案,但我需要调整解析后的一些值
_entry
。
您可以使用
set_axis
:
>>> sr = pd.Series(list('ABCDEF'))
0 A
1 B
2 C
3 D
4 E
5 F
dtype: object
>>> sr.set_axis(range(8, 14))
8 A
9 B
10 C
11 D
12 E
13 F
dtype: object