





Прочитайте его в список списков и преобразуйте после. Я не уверен, почему так много людей боятся предварительной обработки своих данных, чтобы они соответствовали пандам, но это должно быть общей стратегией.
import pandas as pd
headers = []
rows = []
for line in open('x.csv'):
line = line.strip()
if len(headers) < 3:
headers.append(line)
continue
if not rows or len(rows[-1]) == 3:
rows.append([])
rows[-1].append(line)
df = pd.DataFrame(rows, columns=headers)
print(df)
Выход:
feature1 feature2 feature3
0 f1_v1 f2_v1 f3_v1
1 f1_v2 f2_v2 f3_v2
Вы можете сначала прочитать все строки, а затем использовать numpy, чтобы изменить их форму:
import pandas as pd
import numpy as np
with open('text.csv', 'r') as f:
data = f.readlines()
data = list(map(lambda x: x.strip(), data))
data = np.array(data).reshape(3, -1)
data = pd.DataFrame(data[1:, :], columns=data[0])
data.head()
import pandas as pd
# Read the CSV file into a pandas DataFrame
df = pd.read_csv('filename.csv')
# Reshape the DataFrame using pivot_table()
new_df = pd.pivot_table(df, index=df.index // 3, columns='feature1', values='value')
# Rename the column axis to None to remove the "feature1" label
new_df.columns.name = None
# Display the new DataFrame
print(new_df)
and this is how you would change it depending on the amount of values in the rows
import pandas as pd
# Read the CSV file into a pandas DataFrame
df = pd.read_csv('filename.csv')
# Reshape the DataFrame into "long" format
long_df = pd.melt(df, id_vars=['feature1'], value_vars=['feature2', 'feature3'], var_name='feature', value_name='value')
# Reshape the DataFrame using pivot_table()
new_df = pd.pivot_table(long_df, index=long_df.index // 2, columns='feature', values='value')
# Rename the column axis to None to remove the "feature" label
new_df.columns.name = None
# Display the new DataFrame
print(new_df)
Прочитайте CSV в список списков, а затем преобразуйте его в фрейм данных.