简体   繁体   English

Python Pandas DataFrame 将每一行的列转换为单个列作为 Pandas 系列

[英]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) 中,每一行都是 P​​andas.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.

相关问题 将 pandas dataframe 中的每一行转换为 dataframe,其中一列在每一行中包含先前在单独列中的值数组 - Convert each row in pandas dataframe to a dataframe with one column containing in each row an array of values previously in seperate columns 为什么 Pandas 将 DataFrame 的一行(或一列)转换为系列? - Why Does Pandas Convert One Row (or Column) of a DataFrame to a Series? Python Pandas 将一列的月/年 dataframe 转换为 dataframe,其中每行为一年 - Python Pandas convert month/year dataframe with one column to dataframe where each row is one year 如何将单列 Pandas DataFrame 转换为 Series - How to convert a single column Pandas DataFrame into Series Pandas数据框:将列转换为单列的行 - Pandas dataframe: convert columns into rows of a single column Python DataFrame 将类型为 pandas.core.series.Series 的两列合并为单列 - Python DataFrame Combine Two Columns with type pandas.core.series.Series into a Single Column 在 pandas python 中将单行转换为不同的 dataframe - Convert a single row into a different dataframe in pandas python 将一系列字符串连接成 Pandas Dataframe 列中的单个字符串(对于每一行)? - Concatenating a series of strings into a single string within a Pandas Dataframe column (for each row)? python,如何将熊猫系列转换为熊猫DataFrame? - python, how to convert a pandas series into a pandas DataFrame? Pandas dataframe 将多行和多列转换为单行[key]和列[key] - Pandas dataframe convert multiple rows and columns to single row[key] and column[key]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM