[英]Python Pandas DataFrame convert columns of each row to one single column as Pandas Series
I am trying to get the data of Pandas.DataFrame (df) into the shape (3,1) with each row being a Pandas.Series.我试图将 Pandas.DataFrame (df) 的数据放入形状 (3,1) 中,每一行都是 Pandas.Series。 When I run my code I keep getting NaN in every single cell instead of the Pandas.Series.
当我运行我的代码时,我一直在每个单元格中得到 NaN,而不是 Pandas.Series。
import pandas as pd
import numpy as np
df = pd.DataFrame(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]),columns=['a', 'b', 'c'])
s = pd.DataFrame(np.zeros(len(df.index))) #creates desired shape
for index, row in df.iterrows():
print(row)
s.iloc[index] = pd.Series(row)
s.head()
This might be what you want这可能是你想要的
X_train = np.array(pd.Series(df.values.tolist())).reshape(3, 1)
print(X_train.shape)
(3, 1)
You shouldn't set the location to a value.您不应将位置设置为值。 Instead consider creating a DataFrame as
而是考虑将 DataFrame 创建为
s = pd.DataFrame(columns=['new_column']) # Empty Dataframe with 1 Column
Then you can append your rows with然后你可以附加你的行
s = s.append({'new_column': row}, ignore_index=True) # Add the Series as an Element
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.