简体   繁体   English

将 DataFrame 附加为新列

[英]Append a DataFrame as a new column

I have the following piece of code:我有以下一段代码:

rev = input(rev: )
def ds():
    data = pd.read_excel(r'H:\sysfile.xls', skiprows=2)
    dataset1 = pd.DataFrame(data, columns=['Col_1', 'Col_2', 'Col_3', 'Col_4'])
    dataset2 = pd.DataFrame(data, columns=['Col_5'])
    dataset2['Col_5'] = dataset2['Col_5'].fillna(rev)

ds()

Col_5 is an existing Column in the xls File. Col_5 是xls文件中的现有列。 I want to give every cell in the column the input from rev If I print() the dataset1 i get the content of the existing DataFrame (read from the xls -File):我想给在列的每一个细胞从输入rev如果我print()dataset1我得到的数据框现有的内容(从读xls -文件):

   A    B    C
0  x    y    z
1  x    y    z
2  x    y    z

Now I want to write the userinput from rev=input() into DataFrame dataset2 and append it to dataset 1 .现在我想将用户rev=input()rev=input()写入 DataFrame dataset2并将其附加到dataset 1

INPUT:输入:

>>>rev: h

Should become this ( dataset2 ):应该变成这个( dataset2 ):

    D
0   h
1   h
2   h

and appand to dataset1 :并附加到dataset1

   A    B    C    D
0  x    y    z    h
1  x    y    z    h
2  x    y    z    h

I need help!我需要帮助!

You can get Transpose of your data frame and add that column as a row.您可以获得数据框的转置并将该列添加为一行。

After adding that row you can use Transpose again to transform your data frame to its normal form添加该行后,您可以再次使用 Transpose 将数据框转换为其正常形式

If you managed already to fill the dataset2 with the user input, what you need is to join both datasets:如果您已经设法用用户输入填充 dataset2,您需要的是加入两个数据集:

dataset1 = pd.DataFrame({'A': ['X', 'X', 'X', 'X'], 'B': ['Y', 'Y', 'Y', 'Y'], 'C': ['z', 'z', 'z', 'z']})

Out[5]: 
   A  B  C
0  X  Y  z
1  X  Y  z
2  X  Y  z
3  X  Y  z

dataset2 = pd.DataFrame({'D': ['h', 'h', 'h', 'h']})

Out[8]: 
   D
0  h
1  h
2  h
3  h

At this point you need to join them:此时你需要加入他们:

result = pd.concat([df1, df2], axis=1, sort=False)

Out[10]: 
   A  B  C  D
0  X  Y  z  h
1  X  Y  z  h
2  X  Y  z  h
3  X  Y  z  h

You can read it in here for further details: https://pandas.pydata.org/pandas-docs/stable/user_guide/merging.html您可以在此处阅读以获取更多详细信息: https : //pandas.pydata.org/pandas-docs/stable/user_guide/merging.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM