I have such .txt file:
| Field | Value |
| ------------ | ------------ |
| First | 1 |
| Second | alfa |
| | |
| First | 23 |
| Second | beta |
| | |
| First | 55 |
| Second | omega |
I need to read and transform this file to get data like this:
| First | Second |
| ------------ | ------------ |
| 1 | alfa |
| 23 | beta |
| 55 | omega |
I start with this:
file = './data.txt'
df = pd.read_csv(file, sep='\t',header=None, skiprows=89, skipfooter=11, engine='python')
df = df.pivot(values=1, columns=0)
but it looks as I need to generate some indexes otherwise my pivoted table looks not very well
| First | Second |
| ------------ | ------------ |
| 1 | |
| | alfa |
| 23 | |
| | beta |
| 55 | |
| | omega |
Is any other solution hot to read that data and get the results that I need?
2条答案
按热度按时间x4shl7ld1#
The trick is you need to create common keys for the index. Using .assign create a column named CommonKeys which is the cumcount of grouping on the Fields column. Finally chain functions to pivot and clean up the df.
Output:
58wvjzkj2#
为了使代码正常工作,我必须修改访问.csv文件的方式,因为我没有那么多行。
以下是有关.sort_values的更多信息:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.sort_values.html
希望能有所帮助:)