[英]Dataframe merging using Pandas
This is my code for dataframing for both df1 and df2.这是我的 df1 和 df2 数据帧代码。 I'm trying to merge these df1 and df2.
我正在尝试合并这些 df1 和 df2。 I'm reading in a table with df1 1127 rows and 1 column, df2 with 284403 rows and 2 columns.
我正在阅读一个包含 df1 1127 行和 1 列的表,df2 包含 284403 行和 2 列。
import pandas as pd
df1 = pd.read_table("mass2.txt")
df1.columns =['ID']
print(df1)
df2 = pd.read_table("combined.txt",sep=",")
df2.columns =['Teff','ID']
print(df2)
columns_titles = ["ID","Teff"]
df3=df2.reindex(columns=columns_titles)
print(df3)
df4 = df1.merge(df3, on='ID', how='left')
print(df4)
I need to merge df2 and df1.我需要合并 df2 和 df1。 The column 'ID' has a few similar elements in both df1 and df2.
“ID”列在 df1 和 df2 中都有一些相似的元素。 Using that I need to get the the respective Teff.
使用它我需要获得相应的 Teff。
For example I need an output like this wherever the IDs are same for both df1 and df2例如,只要 df1 和 df2 的 ID 相同,我就需要这样的 output
df1 sample: df1样本:
ID
J22154748 + 4954052
J22154748 + 4954052
J22152631 + 4958343
J22154748 + 4954052
J22154748 + 4954052
AP17515104-3446100
AP17515104-3446100
J05062845 + 4112062
J16142485-3141000
J16142485-3141000
df2 sample: df2样本:
ID Teff
J00000446 + 5854329 4757.323
J00000546 + 6152107 4937.3726
J00000797 + 6436119 4524.269
J00000940 + 5515185 4651.9395
J00001071 + 6258172 4546.092
AP17515104-3446100 4835.6143
J23595676 + 7918072 4333.089
J22154748 + 4954052 4859.9087
Expected output would be something like this.预期 output 会是这样的。
ID Teff
AP17515104-3446100 4835.6143
AP17515104-3446100 4835.6143
J16142485-3141000 4359.9766
J22154748 + 4954052 4859.9087
J22154748 + 4954052 4859.9087
But I end up getting Nan in Teff column when I run my code.但是当我运行我的代码时,我最终在 Teff 专栏中得到了 Nan。 But I get the desired output when I use pd.dataframe and not when I use pd.read_table.
但是当我使用 pd.dataframe 而不是当我使用 pd.read_table 时,我得到了所需的 output。 Is there a reason for this?
是否有一个原因?
Can you try remove all non useful characters?您可以尝试删除所有无用的字符吗?
>>> pd.merge(df1, df2['Teff'], how='inner',
left_on=df1['ID'].replace(r'[^\w+-]', '', regex=True),
right_on=df2['ID'].replace(r'[^\w+-]', '', regex=True))
key_0 ID Teff
0 J22154748+4954052 J22154748 + 4954052 4859.9087
1 J22154748+4954052 J22154748 + 4954052 4859.9087
2 J22154748+4954052 J22154748 + 4954052 4859.9087
3 J22154748+4954052 J22154748 + 4954052 4859.9087
4 AP17515104-3446100 AP17515104-3446100 4835.6143
5 AP17515104-3446100 AP17515104-3446100 4835.6143
You can also use df1['ID'].str.strip()
to remove leading and trailing whitespaces.您还可以使用
df1['ID'].str.strip()
删除前导和尾随空格。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.